当属性值大于一定数量时触发 WPF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1094401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Trigger when property value is greater than a certain amount
提问by Micah
I want to do something like this:
我想做这样的事情:
<ControlTemplate.Triggers>
<Trigger Property="Width" Value=">25">
<!-- Set values here -->
</Trigger>
</ControlTemplate.Triggers>
Anyway to do something like this?
无论如何要做这样的事情?
回答by Daniel
You can use a data trigger and set the binding RelativeSource to Self. Data Triggers allow binding and bindings lets you have converters.
您可以使用数据触发器并将绑定 RelativeSource 设置为 Self。数据触发器允许绑定,绑定让您拥有转换器。
Example:
例子:
<Button Content="I change colour depending on my width for some reason">
<Button.Triggers>
<DataTrigger
Binding="{Binding
Path=Width,
RelativeSource={RelativeSource Self},
Converter={StaticResource isLessThanConverter},
ConverterParameter=50}"
Value="True">
<Setter Property="Button.Background" Value="Red" />
DataTrigger>
Button.Triggers>
Button>
回答by Sergey Aldoukhov
Not without code behind. Usual practice is:
并非没有背后的代码。通常的做法是:
- When working with UI elements, create an IValueConverter and bind to the property using the converter.
- When working with bound data, create a bool property on your data and trigger from that property.
- 使用 UI 元素时,创建 IValueConverter 并使用转换器绑定到属性。
- 使用绑定数据时,请在数据上创建 bool 属性并从该属性触发。
回答by Steven Robbins
Something might have been added in SP1, but the way I've achieved this in the past is with a ValueConvertor that converts the value into a boolean.
SP1 中可能添加了一些东西,但我过去实现这一点的方法是使用 ValueConvertor 将值转换为布尔值。
In your example your convertor would return true if the value was > 25, false otherwise. If that doesn't make sense I can put an example up :-)
在您的示例中,如果值 > 25,您的转换器将返回 true,否则返回 false。如果这没有意义,我可以举一个例子:-)
回答by Bhauraj Biradar
Data Trigger only validates exact value, not validates "evaluated values"(like greater than, less than, addition etc.). you need a converter to convert to exact value.
数据触发器仅验证精确值,而不验证“评估值”(如大于、小于、加法等)。您需要一个转换器来转换为精确值。