WPF 附加属性

1、附加属性:一个属性原来不属于某个对象,但由于某种需求而被后来附加上去。附加属性的本质是依赖属性。

2、附加属性作用:将属性与数据类型解耦,让数据类型的设计的更加灵活。

3、VS 2008中,依赖属性的snippet是propdp,附加属性的snippet是propa,属性的snippet是prop。

4、举个例子,Human,School。Human中的一个人,他如果在学校里,就会有成绩等;如果在公司里,他就有部门等。此时的成绩和部门就是附加属性。

代码如下:School类

class School:DependencyObject
{
 
    public static int GetGrade(DependencyObject obj)
    {
        return (int)obj.GetValue(GradeProperty);
    }
 
    public static void SetGrade(DependencyObject obj, int value)
    {
        obj.SetValue(GradeProperty, value);
    }
    public static readonly DependencyProperty GradeProperty =
        DependencyProperty.RegisterAttached("Grade", typeof(int), typeof(School), new UIPropertyMetadata(0));
}

Human类

class Human:DependencyObject
{
 
}

 附加属性的使用

private void Button_Click(object sender, RoutedEventArgs e)
{
    Human human = new Human();
    School.SetGrade(human, 6);
    int grade = School.GetGrade(human);
    MessageBox.Show(grade.ToString());
}

 5、当然附加属性也可以使用Binding依赖在其他数据对象上。

原文地址:https://www.cnblogs.com/btbear/p/3383735.html