深入显出WPF 第二部分(14)

深入浅出WPF 第二部分(14)

7.3 附加属性(Attached Properties)

附加属性是说一个属性本来不属于某个对象,但由于某种需求而被后来附加上。也就把对象放入一个特定环境后对象才具有的属性(表现出来就是被环境赋予的属性)就称为附加属性(Attached Properties)。

Visual Studio用于创建依赖属性的snippet是propdp,用于创建附加属性的snippet是propa。

using System.Windows;

namespace FirstWpfApplication.Objects
{
    class School : DependencyObject
    {
        //IDE feature propa

        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 UIPropertyMetadata(0));
    }
}

        private void buttonLogin_Click(object sender, RoutedEventArgs e)
        {
            Student stu = new Student();
            School.SetGrade(stu, 1);

            int grade = School.GetGrade(stu);

            MessageBox.Show(grade.ToString());
        }