Determining When A DependencyProperty Value Changes in WPF

Maybe you wondered why DependencyObject class from WPF doesn’t implement INotifyPropertyChanged interface, but still (somehow almost magical) the WPF bindings work as expected on any DependencyProperty of a DependencyObject instance: the value updates are generating updates to the binding target.

Maybe at some point you will need to run some custom code when a DependencyProperty value changes for a DependencyObject instance, and of course, you may want to do that without a Binding. Well, how could you do that?

You need to use the DependencyPropertyDescroptor.FromProperty method and then the AddValueChanged method of its result to add your own event handler for value changes; it’s easy:

DependencyPropertyDescriptor.FromProperty(MyType.MyProperty, typeof(MyInstanceType)).AddValueChanged(myInstance, OnMyPropertyChanged);

private void OnMyTypeChanged(object sender, EventArgs e)


In the code above, MyType is the name of a type inheriting from DependencyObject that defines the DependencyProperty named MyProperty; MyInstanceType is the name of the type of myInstance object that you want to get the value change events for. Of course, many times MyType will be the same as MyInstanceType: these values can be different only for attached properties.


About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in Computers and Internet. Bookmark the permalink.

2 Responses to Determining When A DependencyProperty Value Changes in WPF

  1. John Lagonikas says:

    Just to let you know, this solution can easily lead to memory leaks. DependencyPropertyDescriptor keeps a dictionary of all objects providing the target DependencyProperty, thus creating hard references to these objects. This leads to circular dependencies in runtime, which retain objects in Gen2 forever. Check out this link for more information:

    I am currently looking for a better solution to the problem (this is how I stumbled upon your blog entry).

  2. Sorin Dolha says:

    If you call RemoveValueChanged(myInstance, OnMyPropertyChanged) when you’re done with listening to the property changes, it shouldn’t generate memory leaks, because the object would then be removed from the internal Dictionary at that time. At least that’s how I assume it should behave.

    Anyway, here are some alternative approaches to this:

Add a reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s