How to listen for Changes in Dependency Properties

Hi guys. Do you know that WPF bindings feature requires target properties to implement special type of WPF specific property – dependency property.

If you have some experience with WPF, this should not be surprise for you. Here I’m going to show how you can utilize this type of property in order to listen for changes in it. Let’s get started.

Here is how we can access registered dependency property for particular type:

var backgroundProperty = TextBox.BackgroundProperty;

The next step is to attach listener by using needed dependency property and needed object instance:

DependencyPropertyDescriptor textDescriptor = DependencyPropertyDescriptor.FromProperty( TextBox.TextProperty, typeof(TextBlock)); TextBox targetTextBox = new TextBox(); textDescriptor.AddValueChanged(targetTextBox, OnTextChanged); private void OnTextChanged(object sender, EventArgs eventArgs) { // Do something. }

As you can see, the first step is to get instance of DependencyPropertyDescriptor and then call its AddValueChanged method which requires target instance and a delegate of type EventHandler.

Now, whenever Text property of TextBox is changing, method OnTextChanged will be called.

This is my first post. I hope to see some comments and subscriptions, so don’t hesitate and go directly RSS feed.