依赖属性

与定义普通的.NET属性不同,依赖属性有自己独特的声明语法和专有的读写属性值的方法。在VisualStudio中,快捷键 propdp + 双Tab能够生成依赖属性的模板代码,这十分方便。
类DependencyEmployeed定义一个依赖属性

public class DependencyEmployee : DependencyObject
{
    public string Email
    {
        get { return (string)GetValue(EmailProperty); }
        set { SetValue(EmailProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Email.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty EmailProperty =
        DependencyProperty.Register("Email", typeof(string), typeof(DependencyEmployee), new PropertyMetadata(""));
}

  • 首先,定义依赖属性的对象必须继承了拥有读写依赖属性值方法GetValue和SetValue的DependencyObject,否则即使对象内部声明了依赖属性但是用不了。
    public object GetValue(DependencyProperty dp);
    public void SetValue(DependencyProperty dp, object value);
    

  • public static readonly DependencyProperty EmailProperty:public static readonly 是必须的,EmailProperty是依赖属性的名称,约定以Property结尾。

  • 下面是构造一个DependencyProperty实例的语法:
    public static DependencyProperty Register(string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata, ValidateValueCallback validateValueCallback);
    
    DependencyProperty的构造函数是private的,我们不能new DependencyProperty()构造一个实例,可以通过DependencyProperty.Register()返回一个实例。
    Register参数释义:
    name: 标识符,一般是依赖属性名称去掉Property后的字符串(该例中EmailProperty去掉Property后的Email.)。标识符必须在类中保证唯一,比如类声明了N个DependencyProperty,那么必须保证这N个DependencyProperty的name各不相同。
    propertyType: DependencyProperty的.NET类型
    owerType: 声明该DependencyProperty的类(该例中是DependencyEmployee)
    PropertyMetadata:
    validateValueCallback:

为什么引入依赖属性概念

posted @ 2024-01-22 00:44  Jchkds  阅读(9)  评论(0编辑  收藏  举报