5. 完整的自定義依賴屬性

5.1 定義

/// <summary>/// 標識 Title 依賴屬性。/// </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>/// 標識 Content 依賴屬性。/// </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){}

以上代碼為一個相對完成的依賴屬性例子(還有一些功能比較少用就不寫出了),從這段代碼可以看出,自定義依賴屬性的步驟如下:

    網(wǎng)友評論