我应该使用 WPF 转换器还是触发器? [英] Should I use WPF converter or trigger?
问题描述
我想知道您如何决定何时使用 converters
以及何时使用 triggers
.我更喜欢在 GUI 上使用触发器进行操作(例如显示/隐藏控件、更改其外观等).
I was wondering how do you decide when to use converters
and when to use triggers
.
I prefer using a triggers for operations on GUI (like showing/hiding controls, changing their appearance etc.).
前段时间我为此使用了 BooleanToVisibilityConverter
但现在,我只是不需要它,我使用触发器来完成与 visibility
相关的所有事情我什至开始思考MS 团队创建 BooleanToVisibilityConverter
的目的是什么?". 通常,如果可能,我会尝试使用声明性方式编写代码 - 在本例中 - XAML.
Some time ago I used a BooleanToVisibilityConverter
for this purpose but now, I just don't need it, I do all things connected to the visibility
using a triggers and I even started to think "what was the purpose of creating a BooleanToVisibilityConverter
by the MS team?". Generally, when it's possible I try to use a declarative way to write the code - in this example - XAML.
您对此有何看法?
推荐答案
我同意你的看法,我也尝试在 XAML 中使用声明性代码并且更喜欢 Triggers
而不是 Converters
>.
I agree with you, I also try to use declarative code in XAML and prefer Triggers
instead of Converters
.
在大多数情况下,触发器可以执行与任何转换器相同的工作,但 转换器
可以具有 pchajer 提到的自定义/业务逻辑.
In most of the scenarios triggers can perform the same work as any converter but Converters
can have custom/business logic as pchajer mentioned.
Triggers
的一个限制是 DataTriggers
中的 Setter 只能更改 UI 元素的属性;所以,你不能用触发器更新你的 ViewModels 属性,这就是 Converters
获胜的地方,记住 ConvertBack
方法.
One limitation of Triggers
is that Setters in your DataTriggers
can only change properties of your UI elements; so, you can't update your ViewModels property with triggers, thats where Converters
win, remember the ConvertBack
method.
因此,您可以使用 BooleanToVisibilityConverter
将您的 VM 属性与控件 Visibility
绑定,即使您的控件 visibility
被更改为其他一些意味着您的 VM 属性将得到更新;通常不需要,这就是 BooleanToVisibilityConverter
被触发器替换的原因.
So, you can bind your VM property with a controls Visibility
using BooleanToVisibilityConverter
and even if your controls visibility
is changed by some other means your VM property will get updated;
generally it's not required that's why BooleanToVisibilityConverter
gets replaced by triggers.
简而言之 -
Triggers
只能执行 OneWay
操作,而 Converters
可以执行 TwoWay
操作
Triggers
can only performOneWay
operations whereasConverters
can performTwoWay
operations
这篇关于我应该使用 WPF 转换器还是触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!