Dutton

Hooking into changes on a Dependency Property on an object that's not yours

I came across a scenario today where I needed to hook into dependency property changes on an object that wasn't mine and found this new trick I'd not seen before, you can get the property's descriptor and add a new value changed handler in code.

var descriptor = DependencyPropertyDescriptor.FromProperty(RadioButton.IsCheckedProperty, typeof(RadioButton));
descriptor.AddValueChanged(radioButton, (s,e) => { /* ... */ });

Don't forget to remove the handler again once you're finished with it to prevent memory leaks like so.

descriptor.RemoveValueChanged(...);

Share this: