public class DPCustomPeople { public static readonly DependencyProperty AgeProperty = DependencyProperty.Register("Age", typeof(int), typeof(DPCustomPeople));
class Program { static void Main(string[] args) { DPCustomPeople people = new DPCustomPeople(); people.DisplayAgeProperty(); } } 你可能对DependencyProperty类比较陌生,DependencyProperty类提供了依赖属性的一些基本特征
四.属性元数据(PropertyMetadata) MSDN原话:Windows Presentation Foundation (WPF) 属性系统包括一个元数据报告系统,该系统不局限于可以通过反射或常规公共语言运行时 (CLR) 特征报告的关于某个属性的内容。
说到属性元数据,第一个让人想到的就是.net的Attribute
public class Person { [DefaultValue(200),Category("Layout")] public int Width { get; set; } } Attribute需要借助Visual Studio的力量,使得IDE对Attribute进行很友好的支持,或者依靠反射来赋值.
public bool IsBoy { get { return (bool)GetValue(IsBoyProperty); } set { SetValue(IsBoyProperty, value); } }
public static readonly DependencyProperty IsBoyProperty = DependencyProperty.Register("IsBoy", typeof(bool), typeof(Student), new UIPropertyMetadata(false,new PropertyChangedCallback(IsBoyPropertyChangedCallback)));
public static void IsBoyPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { Student st = d as Student; if (st.IsBoy) { Console.WriteLine("Hello,Boy"); } else { Console.WriteLine("Hello,Girl"); } }
public static readonly DependencyProperty IsBoyProperty = DependencyProperty.Register("IsBoy", typeof(bool), typeof(Student), new UIPropertyMetadata(null,new PropertyChangedCallback(IsBoyPropertyChangedCallback))); 再来看看引用类型,默认值为null则相安无事
public IList LovedGirl { get { return (IList)GetValue(LovedGirlProperty); } set { SetValue(LovedGirlProperty, value); } }
public static readonly DependencyProperty LovedGirlProperty = DependencyProperty.Register("LovedGirl", typeof(IList), typeof(Student), new UIPropertyMetadata(null, new PropertyChangedCallback(LovedGirlChangedCallback)));
public static void LovedGirlChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { Student st = d as Student; foreach (var item in e.NewValue as IList) { Console.WriteLine(item); } }
public void TestReferenceDpType() { List<string> list = new List<string>(); list.Add("girl 1"); list.Add("girl 2"); this.LovedGirl = list; } 4.强制属性回调
首先默认值还是不会触发回调方法.
强制回调方法即不管属性值有无发生变化,都会进入回调方法
public int Score { get { return (int)GetValue(ScoreProperty); } set { SetValue(ScoreProperty, value); } }
public static readonly DependencyProperty ScoreProperty = DependencyProperty.Register("Score", typeof(int), typeof(Student), new UIPropertyMetadata(0,null,new CoerceValueCallback(ScoreCoerceValueCallback)));