Search code examples
c#wpfdependency-propertiesreadonlyinotifypropertychanged

Add PropertyChangedCallback to a readonly dependency property of the base class


I need to register a property changed callback method to IsHighlighted property of a menuitem.
But on executing I get an exception that says that IsHighlighted is registered as readonly.

Any ideas to add the callback method, or is there another way to check the property changing?

public class MyMenuItem : MenuItem
{
    static MyMenuItem()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyMenuItem),
            new FrameworkPropertyMetadata(typeof(MyMenuItem)));
        
        /* IsHighlighted was registered as readonly and is not possible 
        override metadata without an authorization key. */
        IsHighlightedProperty.OverrideMetadata(typeof(MyMenuItem),
            new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnIsHighlightedChanged)));
    }

    private static void OnIsHighlightedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {

    }
}

Solution

  • I've resolved by using DependencyPropertyDescriptor.

    DependencyPropertyDescriptor.FromProperty(IsHighlightedProperty, typeof(MyMenuItem))
        ?.AddValueChanged(this, (s, e) => OnHighlightChanged(IsHighlighted));