WPF——自定义控件——继承DependencyProperty和PropertyChangedCallback

WPF – Custom Control – Inherited DependencyProperty and PropertyChangedCallback

在像下面这样的自定义控件的情况下,如何为继承的DependencyProperty添加PropertyChangedCallback IsEnabledProperty?

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 += …
      }
}

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

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

您不需要在所有情况下都这样做。您可以在自定义 class:

的构造函数中执行
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/

这个有效:

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