Cool trick with Dependency Properties

One of the cool things about dependency properties is that they allow other things to be dependent on them and notified of changes to them (hence their name). However, one thing that people will sometimes stumble upon is that they want to know about a change to a particular property value but WPF does not expose this event.

Every time I have found the code for this I have thought "Cool!" and then a couple of months later I forget it again. Now that I don't write WPF code all day every day anymore (sniff) I have even less of a chance of remembering it. So I post it here for myself to find later and as a gift to anybody who reads it.

The trick is to use DependencyPropertyDescriptor. If you have the DependencyProperty already (normally a static member of the class, such as WidthProperty) then you can call DependencyPropertyDescriptor.FromProperty and pass that in. Once you have the DependencyPropertyDescriptor you can call AddValueChanged to subscribe to the change event.

Now Bob's your mum's brother. Remember though, for your own properties you can register a change event handler in the metadata yourself to avoid writing this.

Comments

  • Anonymous
    February 02, 2007
    Outstanding!
  • Anonymous
    February 07, 2007
    The comment has been removed
  • Anonymous
    April 28, 2008
    Just be sure you unregister or you will cause a memory leak.