Search code examples
c#wpfxaml.net-7.0

WPF - Why is there no OnForegroundChanged method in Control?


I am overriding ContentControl which inherits from Control which has dep prop Foreground.. I want to run some custom logic on foreground changed event but there is no OnForegroundChanged method to override. There are dozens of other properties changed event handlers but not foreground. Is this by design or am I missing something?

P.S. I need dependency property event handler only, I am not looking for any other solutions


Solution

  • There are no events notifying that any property has changed, but events are not the only way to receive notifications. For example, Binding will receive notification when any Dependency Property changes. And to do this, it does not need to create a derived element with an additional event.

    The easiest way to listen for a Dependency Property change is to use a DependencyPropertyDescriptor:

        var descriptor = DependencyPropertyDescriptor.FromProperty(ForegroundProperty, control.GetType());
        descriptor.AddValueChanged(control, OnForegroundChanged);
    

    OnForegroundChanged - value change listener method.

    P.S. Be careful when using this method with many objects being added or removed. The AddValueChanged method creates a strong reference to the listener method (in the example it is OnForegroundChanged). And if it is an instance method, then that instance will be held in memory until RemoveValueChanged is called. If you don't do this, there is a possibility of a memory leak.