如何在XAML中将DependencyProperty重置为默认值 [英] How do I reset a DependencyProperty back to it's default value in XAML
问题描述
我正在使用滑块实现用户可调的效果
,并且滑块旁边有一个重置按钮。想法是允许用户重置为元数据中指定的 Effect
属性的默认值。
I'm implementing a user-adjustable Effect
using sliders and I have a reset button beside the slider. The idea is to allow the user to reset back to the default value of the Effect
's property as specified in metadata.
我认为在XAML中这样做很简单。
I think it might be trivial to do that in XAML.
推荐答案
依赖项属性实际上没有默认值。如果依赖项属性没有局部值,则它将通过值继承或强制转换来获取其值,具体取决于属性的实现方式。
Dependency properties don't really have default values. If a dependency property doesn't have a local value, it will obtain its value either through value inheritance or through coercion, depending on how the property has been implemented.
您无法真正摆脱XAML中属性的局部值-这将要求您在属性上调用 ClearValue
,并且无法找到对象并调用方法在声明上。但是,只要该属性通过价值继承(而不是价值强制)获得其价值,就可以通过将属性绑定到在适当的祖先上继承的属性来从根本上完成同一件事。
You can't really get rid of the property's local value in XAML - that would require you to call ClearValue
on the property, and there's no way to find the object and call a method on it declaratively. But as long as the property's getting its value through value inheritance (instead of value coercion) - you can accomplish fundamentally the same thing by binding the property to the property it's inheriting from on the appropriate ancestor
例如,这是一种用于创建 ListBox
的样式,该样式设置所有没有的项目的前景色>已选择:
For instance, here's a style you'd use to create a ListBox
that sets the foreground color of all items that aren't selected:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Foreground" Value="Red"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter
Property="Foreground"
Value="{Binding
RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox},
Path=Foreground}" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
这基本上是通过绑定显式实现值继承。这确实意味着 ListBoxItem.Foreground
属性现在具有一个本地值,并且每当您更改 Foreground
ListBox
上的code>属性是它的绑定,它会更新 ListBoxItem.Foreground
而不是依赖项属性系统。如果 ListBox
中有成千上万个项目,这实际上可能很重要。但是在大多数实际情况下,您永远都不会注意到差异。
This basically explicitly implements value inheritance through binding. It does mean that the ListBoxItem.Foreground
property now has a local value, and that whenever you change the Foreground
property on the ListBox
it's binding that updates the ListBoxItem.Foreground
and not the dependency-property system. This might actually matter if you have hundreds of thousands of items in your ListBox
. But in most real-world cases, you'll never notice the difference.
这篇关于如何在XAML中将DependencyProperty重置为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!