Attaching Event Handlers to Dependency Properties

In the previous articles, we investigated how to create dependency properties. Beside binding them to properties in XAML, it is useful to attach event handlers to them to be notified about change events. The example code for this article is in the WpfWednesday git repository, in the Z08_AttachingEventHandlers project.

There are two methods to attach event handlers to a dependency property:

  1. During the registration of the dependency property. This is only achievable if we have control over the registration of the property.
  2. By using the DependencyProperty object itself.

Let’s review these methods.

Attaching event handler to a dependency property during registration

This can be achieved by providing an event handler method to the second parameter of the PropertyMetadata object during the registration of the DependencyProperty.

Let’s look the following example code:

In the above code the event handler is registered by the code block below:

This method has the benefit of receiving a DependencyPropertyChangedEventArgs, which will contain the new value and the old value of the property changed.

Attaching event handler by using the DependencyProperty object itself

With this method, we can attach an event handler to the changing value of the dependency property by using the commonly declared <PropertyName>Property property.

The example code below will attach to a change event of the Result property in the MultiplyByTwo class above.

First, we access the DependencyPropertyDescriptor object associated with the property by executing the following code:

Then we attach the event handler by adding an AddValueChangedHandler with the use of the actual object that we want to observe:

Because the required information for this type of event handler attachment is available through the .NET Framework and it is a good practice to provide it, it is easy to accomplish this. The only drawback is that in this form of event handler attaching we will only access EventArgs event arguments. This argument structure does not provide information about the previous state of the property.

Finally, here is a test code to test both approaches above:

You can connect with me on LinkedIn, Twitter or you can register on the blog. Share if you found this article useful or know somebody who would benefit from reading it.

By subscribing to the email list, you will be notified about new posts.

No comments yet.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Powered by WordPress. Designed by WooThemes