Another Way To Listen To DP Value Change

|

Ben Constable just blogs about another elegant way to listen to dependency property change, the trick here is using DependencyPropertyDescriptor, imagine that you have a Label called myLabel, and you want to get notified when it's ContentProperty is changed, then you can do something like the following:

DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(Label.ContentProperty, typeof(Label));
if (dpd != null)
{
    dpd.AddValueChanged(myLabel, delegate
    {
        // Add your logic here to respond to value change.
    });
}

The other ways in WPF that you can use to listen to property change is to subclass an existing Control, and override the metadata of a dependency property whose property change you want to listen to, when you do so, you need to specify a PropertyChangedCallback which a delegate to your property change event handler, or instead of using PropertyChangedCallback, you can override the OnPropertyChanged method, and place your logic there, as a bonus, you can get additional information things like which property is changed by examining the value of passed-in DependencyPropertyChangedEventArgs argument's Property property.

0 comments: