This documentation is archived and is not being maintained.

How to: Restore the Default Value of a Dependency Property

This example shows how to use the ClearValue method to reset dependency property values to their default value.


The following example clears the locally set property values within several types of Shape elements. The RestoreDefaultProperties user-defined method shown in the example deliberately iterates all the read/write dependency properties that are locally set and clears each one. Local values for the properties were established (using XAML attribute syntax) in a loaded XAML page (not shown). After RestoreDefaultProperties runs, the effective values for those properties is determined by the Setter values that are contained in the styles for that Shape type.

Note that the default value for a dependency property is not necessarily the DefaultValue that is established in the metadata for that dependency property. Other factors are still active and they can become the source for the effective property value after the local value is cleared.

void RestoreDefaultProperties(object sender, RoutedEventArgs e)
    UIElementCollection uic = Sandbox.Children;
    foreach (Shape uie in uic)
        LocalValueEnumerator locallySetProperties = uie.GetLocalValueEnumerator();
        while (locallySetProperties.MoveNext())
            DependencyProperty propertyToClear = (DependencyProperty)locallySetProperties.Current.Property;
            if (!propertyToClear.ReadOnly) { uie.ClearValue(propertyToClear); }

For the complete sample, see Restoring Default Values Sample. The complete sample that this example is derived from includes implicit styles for each Shape type. After the ClearValue call clears the local value, the style for each Shape determines property values for the specific properties that were cleared. The metadata-based DefaultValue of those properties operates at a lower value determination precedence than the styles do, therefore the DefaultValue is not used even after the values are cleared. For more information about value precedence for dependency properties, see Dependency Property Value Precedence. Be sure to run the Restoring Default Values Sample to see how the style applies the value.

See Also