相依性屬性最特別的是屬性變更事件(Property Changed Events)的功能,目的是提供一個依據其他輸入值來計算屬性值的方法,有了相依性屬性WPF才能夠設定資源(Resources)、樣式(Styles)、動畫(Animations)與資料繫結(Data Binding)等功能。
與一般.NET屬性互相比較,程式使用撰寫上沒有什麼差異,但底層實作卻完全不同。因此,通常會研究相依性屬性是為了自訂相依性屬性,接下來我們介紹自訂的方法。
假設我們自訂一個相依性屬性是My(型別為Int32),那麼程式會定義一個DependencyProperty型態的MyProperty屬性(欄位的名稱一定要是屬性的名稱附加上後置字元 Property),注意必須是public static readonly的。
class MyClass{
public static readonly DependencyProperty MyProperty;
}
必須用DependencyProperty.Register方法的初始化,直接於宣告時設定,或是在類別的建構函式中(宣告為靜態的建構函式)。public static readonly DependencyProperty MyProperty= DependencyProperty.Register( "My", typeof(Int32), typeof(MyClass) );
public Int32 My
{
get { return (Int32)GetValue(MyProperty); }
set { SetValue(MyProperty, value); }
}
若是要加入更完整的相依性屬性功能,則需要屬性中繼資料(Metadata),利用PropertyMetadata類別宣告,通常是設定預設值(如設定為0),或是加入屬性變更事件回呼函式(PropertyChangedCallback)。public static readonly DependencyProperty MyProperty= DependencyProperty.Register(
"My",
typeof(Int32),
typeof(MyClass),
new PropertyMetadata(0, new PropertyChangedCallback(OnMyChanged))
);
private static void OnMyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
//當屬性值改變要執行的程式碼
}
相依性屬性大致上常用到上述的四個功能,其他像是屬性值驗證、繼承等進階深入議題,請參閱MSDN資料。http://msdn.microsoft.com/zh-tw/library/ms753192(v=VS.90).aspx
###
沒有留言:
張貼留言