5. 完整的自定義依賴(lài)屬性
5.1 定義
/// <summary>/// 標(biāo)識(shí) Title 依賴(lài)屬性。/// </summary>public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(MyPage), new PropertyMetadata(string.Empty));/// <summary>/// 獲取或設(shè)置Content的值/// </summary> public object Content{ get { return (object)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); }}/// <summary>/// 標(biāo)識(shí) Content 依賴(lài)屬性。/// </summary>public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(object), typeof(MyPage), new PropertyMetadata(null, OnContentChanged));private static void OnContentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args){ MyPage target = obj as MyPage; object oldValue = (object)args.OldValue; object newValue = (object)args.NewValue; if (oldValue != newValue) target.OnContentChanged(oldValue, newValue);}protected virtual void OnContentChanged(object oldValue, object newValue){}
以上代碼為一個(gè)相對(duì)完成的依賴(lài)屬性例子(還有一些功能比較少用就不寫(xiě)出了),從這段代碼可以看出,自定義依賴(lài)屬性的步驟如下: