WPF 依赖属性与附加属性

DependencyProperty: IDE快捷键propdp

 

        <TextBox x:Name="textBox1"/>

 

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;



namespace WpfApplication8

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            MyClass myClass = new MyClass() { My = "123123" };

            textBox1.SetBinding(TextBox.TextProperty, new Binding() { Source = myClass, Path = new PropertyPath(".My") });

        }

    }



    public class MyClass : DependencyObject

    {

        public static readonly DependencyProperty MyProperty = DependencyProperty.Register("My", typeof(string), typeof(MyClass));

        public string My

        {

            get { return this.GetValue(MyProperty).ToString(); }

            set { this.SetValue(MyProperty, value); }

        }

    }

}


AttachedProperty IDE快捷键propa

 

 

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            MyClass2 mc2 = new MyClass2();

            MyClass1.SetMyNameProperty(mc2, "hehe");

            string str = MyClass1.GetMyNameProperty(mc2);

        }

    }



    public class MyClass1 : DependencyObject

    {

        public static string GetMyNameProperty(DependencyObject obj)

        {

            return (string)obj.GetValue(MyNameProperty);

        }



        public static void SetMyNameProperty(DependencyObject obj, string value)

        {

            obj.SetValue(MyNameProperty, value);

        }



        // Using a DependencyProperty as the backing store for MyNameProperty.  This enables animation, styling, binding, etc...

        public static readonly DependencyProperty MyNameProperty =

            DependencyProperty.RegisterAttached("MyName", typeof(string), typeof(MyClass1), new UIPropertyMetadata(string.Empty)); 

    }



    public class MyClass2 : DependencyObject

    { }

 

你可能感兴趣的:(WPF)