简体   繁体   中英

WPF – Custom Control – Inherited DependencyProperty and PropertyChangedCallback

In the case of the Custom Control like the following, how to add PropertyChangedCallback for inherited DependencyProperty 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
      }
}

Yes, there is another option like listen to the IsEnabledChangeEvent

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

But I don't like the approach register event handler in every instance. So I prefer the metadata overriding.

This works:

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

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

You don't need to do this in every instance. You could do in the constructor of your custom class:

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

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

Another option is to use a DependencyPropertyDescriptor to peform any action in response to a change to an existing dependency property: https://blog.magnusmontin.net/2014/03/31/handling-changes-to-dependency-properties/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM