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
    { }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值