Compartir a través de


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.

Example

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); }
        }
    }
}
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, 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 theRestoring Default Values Sample to see how the style applies the value.

See Also

Reference

DefaultValue

Concepts

Dependency Property Value Precedence

Other Resources

Restoring Default Values Sample
Properties How-to Topics
Properties Samples