问题
If one is implementing a WPF application using the MVVM design pattern, is there any situation in which to use value converters? It seems to me that value converters do exactly the same what the view model does too, that is preparing data for the view.
So, are there some good uses for value converters?
Best Regards
Oliver Hanappi
回答1:
Value converters are handy to translate logical states into visual states that are only relevant for the UI. A BooleanToVisibility converter, for example, has its place in a MVVM application.
However, I would never recommend to use converters to perform any complex conversion with various input parameters or to call any business logic in their implementation. That's VM stuff.
回答2:
This question is much on my mind, because I wrote a whole slew of value converters for my project before realizing that I could just be doing all of that in my view model. I'm still using them - I'm just not referencing them from XAML; my view model calls them explicitly.
It's actually useful to decouple value conversion from the view model even if you're not going to call the value converters from XAML, and just call them from the view model instead. It makes value conversion logic easier to test, more reusable, and composable. I even use value converters in the data access layer of my model without apparent ill effect.
来源:https://stackoverflow.com/questions/2237834/when-to-use-value-converters-in-a-mvvm-application