Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

.net - Should I use WPF converter or trigger?

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.).

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.

What is your opinion of that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I agree with you, I also try to use declarative code in XAML and prefer Triggers instead of Converters.

In most of the scenarios triggers can perform the same work as any converter but Converters can have custom/business logic as pchajer mentioned.

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.

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.

So in short -

Triggers can only perform OneWay operations whereas Converters can perform TwoWay operations


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...