wpf 依赖属性与附加属性

依赖属性 与 附加属性 相对于 CLR 属性, 他们的值保存于一个 hash 表中, 大量使用时不会占用太多空间
相当基础的类型, wpf 事件 命令 都需要该属性的支持
元素树中的属性值还提供了向下继承的功能,比如设置字体大小 ,子元素也会继承字体大小。但不是所有子元素会继承父元素的属性值,
取值 ValueSource vs2 = DependencyPropertyHelper.GetValueSource(this.sb1, StatusBar.FontSizeProperty);
为后面的事件与命令提供支持

依赖属性

必须在DependencyObject 基类中设置

// 必须在DependencyObject 基类中设置
// 调用 Register

public partial class PropertyControl : DependencyObject 
{    
    public static readonly DependencyProperty XValueProperty = DependencyProperty.Register(
            nameof(XValue), typeof(string), typeof(PropertyControl), new PropertyMetadata(default(string)));

    // 为了兼容 CLR 类, 这里也提供了属性
    public string XValue
    {
            get { return (string)GetValue(XValueProperty); }
            set { SetValue(XValueProperty, value); }
    }   

}

// 使用
 <dependObjectDemo:PropertyControl XValue="1245" />
// 或是 
PropertyControl ctrl = new PropertyControl();
ctrl.XValue = "123"    

附加属性

可以在 DependencyObject 或是非 DependencyObject 子类中定义,
而值却是保存于其它 DependencyObject 的子类对象中
按约定要提供静态函数 GetXXX与 SetXXX , 不然无法在 xaml 中使用
比如常见的 Grid.Column 在 Grid 中定义, 但是在其它控件中设置使用

    # 调用 RegisterAttached
    public static readonly DependencyProperty AttachedProperty = DependencyProperty.RegisterAttached(
        "Attached", typeof(string), typeof(PropertyControl), new PropertyMetadata(default(string)));

    public static string GetAttached(DependencyObject obj)
    {
        return (string)obj.GetValue(AttachedProperty);
    }

    public static void SetAttached(DependencyObject obj, string value)
    {
        obj.SetValue(AttachedProperty, value);
    }

使用
<Grid x:Name="Grid" dependObjectDemo:PropertyControl.Attached="11223" />
或是
var value = this.Grid.GetValue(PropertyControl.AttachedProperty);      

共享属性

不创建新属性,直接使用已有属性

// TextBlock 中的 FontFamilyProperty 使用 TextElement 中已有属性
public class TextBlock
{
        public static readonly DependencyProperty FontFamilyProperty =
            TextElement.FontFamilyProperty.AddOwner(typeof(TextBlock), new UIPropertyMetadata(null));
}
上一篇
下一篇