Tuesday, February 02, 2010

Checking if a WPF property is set or not

I had this scenario where a property was attached to objects but I wanted different default values for different objects. The code made it easy to just check if the property was set or not, then set the default myself. In order to do that, use the DependencyObject.ReadLocalValue instead of DependencyObject.GetValue and then check if the result equals DependencyProperty.UnsetValue. Like this:

return element.ReadLocalValue(MyProperty) == DependencyProperty.UnsetValue;
Of course, this can be used as an extension method for any element and/or property.