Monday, January 21, 2008

Reset a DependencyProperty to its default value

If we have a dependency property:

public static readonly DependencyProperty MyExampleValueProperty = DependencyProperty.Register("MyExampleValue", typeof(double), typeof(MyClass), new PropertyMetadata(3.1592));

public double MyExampleValue
{
   
set { SetValue(MyExampleValuePropertyProperty, value); }
   
get { return (double)GetValue(MyExampleValuePropertyProperty); }
}

After the value has been changed we might reach a point where we want to reset this property to its default value (3.1592). This can be done in two ways:

  • MyExampleValue = (double)MyClass.MyExampleValueProperty.DefaultMetadata.DefaultValue;
  • this.ClearValue(MyClass.MyExampleValueProperty);

But there are some things to note here: If we have a scenario where we want to inherit the value if the dependency property is not set in the current class, then we can not use the first example (MyExampleValue =...). Why? Because we are setting the current instance to a value, so the value will not be inherited (the only thing we are doing is setting the value to the same as the default for the property). In the second example this will work since we are clearing the property instead of setting it.

No comments: