How to: Restore the Default Value of a Dependency Property
This example shows how to use the ClearValue method to reset a dependency property value to its default value.
The following example clears the locally set property values of several types of Shape elements. The RestoreDefaultProperties user-defined method shown in the example finds 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 value for each property is determined by the Setter value that is contained in the style 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.
Private Sub RestoreDefaultProperties(ByVal sender As Object, ByVal e As RoutedEventArgs) Dim uic As UIElementCollection = Sandbox.Children For Each uie As Shape In uic Dim locallySetProperties As LocalValueEnumerator = uie.GetLocalValueEnumerator() While locallySetProperties.MoveNext() Dim propertyToClear As DependencyProperty = locallySetProperties.Current.Property If Not propertyToClear.ReadOnly Then uie.ClearValue(propertyToClear) End If End While Next End Sub
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, so 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.