2017-04-21 63 views
1

自定義控件像下面這樣的情況下,如何添加PropertyChangedCallback爲繼承的DependencyProperty IsEnabledPropertyWPF - 自定義控制 - 繼承的DependencyProperty和PropertyChangedCallback

public class MyCustomControl : ContentControl 
{ 
     // Custom Dependency Properties 

     static MyCustomControl() 
     { 
      DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); 
      // TODO (?) IsEnabledProperty.OverrideMetadata(typeof(MyCustomControl), new PropertyMetadata(true, CustomEnabledHandler)); 
     } 

     public CustomEnabledHandler(DependencyObject d, DependencyPropertyChangedEventArgs e) 
     { 
      // Implementation 
     } 
} 

是的,有喜歡的另一種選擇聽IsEnabledChangeEvent

public class MyCustomControl : ContentControl 
{ 
     public MyCustomControl() 
     { 
      IsEnabledChanged += … 
     } 
} 

但我不喜歡在每一個實例中的方法註冊事件處理程序。所以我更喜歡元數據覆蓋。

+0

OverrideMetadata有什麼問題?但請注意,它應該是FrameworkPropertyMetadata而不是PropertyMetadata。 – Clemens

+0

@Clemens如果我在** XAML **中使用這個控件,我會收到錯誤:_Metadata覆蓋和基礎元數據必須是相同類型或派生類型._我也使用'FrameworkPropertyMetadata'嘗試它。 – David

+0

它適用於FrameworkPropertyMetadata。再試一次。 – Clemens

回答

2

這工作:

static MyCustomControl() 
{ 
    DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), 
     new FrameworkPropertyMetadata(typeof(MyCustomControl))); 

    IsEnabledProperty.OverrideMetadata(typeof(MyCustomControl), 
     new FrameworkPropertyMetadata(IsEnabledPropertyChanged)); 
} 

private static void IsEnabledPropertyChanged(
    DependencyObject obj, DependencyPropertyChangedEventArgs e) 
{ 
    Debug.WriteLine("{0}.IsEnabled = {1}", obj, e.NewValue); 
} 
+0

是的,這是我一直在尋找的,謝謝。還有一個問題。 「IsEnabledProperty」的原始行爲仍然有效?這隻會增加一個回調,對吧? – David

+0

的確如此,但在線文檔中也有詳細說明。 – Clemens

1

But I don't like the approach register event handler in every instance.

您不需要在每個實例中都這樣做。你可以做你的自定義類的構造函數:

public class MyCustomControl : ContentControl 
{ 
    static MyCustomControl() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); 
    } 

    public MyCustomControl() 
    { 
     IsEnabledChanged += (s, e) => { /* do something */ }; 
    } 
} 

另一種選擇是使用DependencyPropertyDescriptor到[執行任何行動響應改變現有的依賴屬性:https://blog.magnusmontin.net/2014/03/31/handling-changes-to-dependency-properties/

+0

是的,我認爲這種方法。我也看着'DependencyPropertyDescriptor' - 但仍然 - 我認爲每個'MyCustomControl'實例都增加了一些對change事件的引用。 – David

+0

當然。每個實例應該如何處理變更......?你認爲OverrideMetdata對你的CustomEnabledHandler有什麼作用? – mm8

+0

我認爲'OverrideMetadata'「共享」實例間回調方法的信息,不是嗎?因此,回調方法需要知道'DependencyObject' - 'CustomEnabledHandler(DependencyObject d,DependencyPropertyChangedEventArgs e)'。 – David

相關問題