WPF附加属性

附加属性实质也是依赖属性,是说一个属性本来不属于某个对象,但由于某种需求被后来附加上的,也就是说把对象放入一个特定环境后才具有的属性

例子:人在学校有年纪和班级两个属性,人放在学校里会获得年级和班级两个属性说明年级和班级两个属性是学校附加给人的。因此这两个属性的真实所有者应该是学校.

VisualStudio快捷键 propa

1.1.自定义附加属性

public class School
    {
        public static int GetGrade(DependencyObject obj)
        {
            return (int)obj.GetValue(GradeProperty);
        }

        public static void SetGrade(DependencyObject obj, int value)
        {
            obj.SetValue(GradeProperty, value);
        }

        // Using a DependencyProperty as the backing store for Grade.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty GradeProperty =
            DependencyProperty.RegisterAttached("Grade", typeof(int), typeof(School), new PropertyMetadata(0)); 
    }
 //自定义附加属性的使用
  Human human = new Human();
  School.SetGrade(human, 6);
  int grade = School.GetGrade(human);
  MessageBox.Show(grade.ToString());
原文地址:https://www.cnblogs.com/come-on-come-on/p/5629872.html