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)));