HOW TO:還原 Dependency 屬性的預設值
更新:2007 年 11 月
本範例示範如何使用 ClearValue 方法,將相依性屬性值重設為預設值。
範例
下列範例會清除本機設定的屬性值,這些值分屬於不同 Shape 項目類型。範例中顯示的 RestoreDefaultProperties 使用者定義會找到本機設定的所有讀取/寫入相依性屬性,並清除每個屬性。屬性 (Property) 的本機值建立於 (使用 XAML 屬性 (Attribute) 語法) 載入的 XAML 頁面 (未顯示)。RestoreDefaultProperties 執行之後,每個屬性 (Property) 的有效值都會由 Setter 值決定,該值包含於該 Shape 類型的樣式。
請注意,相依性屬性的預設值不必是在相依性屬性中繼資料內建立的 DefaultValue。其他係數仍在作用中,且可在清除本機值之後,成為有效屬性值的來源。
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
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); }
}
}
}
如需完整範例,請參閱還原預設值範例。本範例衍生來源的完整範例包含每個 Shape 類型的隱含樣式。在 ClearValue 呼叫清除本機值之後,每個 Shape 的樣式都會決定已清除之特定屬性的屬性值。那些屬性中以中繼資料為基礎的 DefaultValue 在決定優先順序時會低於樣式,因此,即使在清除值之後,也不會使用 DefaultValue。如需相依性屬性值決定優先順序的詳細資訊,請參閱相依性屬性值優先順序。請務必執行還原預設值範例,以檢視樣式顯示值的方式。