对于如下的自定义控件,如何为继承的DependencyProperty IsEnabledProperty添加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 += …
      }
}


但是我不喜欢在每个实例中都注册方法事件处理程序。所以我更喜欢元数据覆盖。

最佳答案

这有效:

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

关于c# - WPF –自定义控件–继承的DependencyProperty和PropertyChangedCallback,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43543643/

10-12 02:04