如何在MVVM模式中使用WPF转换器? [英] How can WPF Converters be used in an MVVM pattern?

查看:91
本文介绍了如何在MVVM模式中使用WPF转换器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个绑定到 ViewModel A 的视图,该视图具有一个可观察的集合 Customers .

Let's say I have a View that is bound to ViewModel A which has an observable collection Customers.

此MVVM模式的一个优点是,我还可以将View绑定到 ViewModel B ,这会用不同的数据填充它.

An advantage of this MVVM pattern is that I can also bind the View to ViewModel B which fills it with different data.

但是如果在我的查看转换器转换器中显示我的客户该怎么办?我有一个"ContractToCustomerConverter",它接受合同并返回要显示的适当客户.

But what if in my View converter Converters to display my customers, e.g. I have a "ContractToCustomerConverter" that accepts a Contract and returns the appropriate Customer to be displayed.

此问题是转换器存在于MVVM模式之外,因此不知道我的ViewModel有另一个客户来源.

The problem with this is that the converter exists outside the MVVM pattern and thus doesn't know that my ViewModel has another source for customers.

  • 视图是否可以将ViewModel传递到Converter 中,从而使其参与MVVM模式提供的去耦?
  • 是否有办法以某种方式在我的ViewModel中包含Converter ,以便该转换器使用ViewModel可用的当前依赖项?
  • 或者是转换器,只是隐藏在代码后面的,因此不在MVVM模式中使用,因此,如果您使用的是MVVM,则只需创建自己的转换器"(ViewModel类上的方法)即可返回诸如Image对象,Visibility对象,FlowDocuments等要在视图上使用的东西,而不是根本不使用转换器?
  • is there a way for the View to pass the ViewModel into the Converter so that it participates in the decoupling that the MVVM pattern provides?
  • is there a way for me to somehow include the Converter in my ViewModel so that the converter uses the current dependencies which ViewModel has available?
  • or are converters just glorified code-behind and thus not used in the MVVM pattern, so if you are using MVVM then you just create your own "converters" (methods on your ViewModel class) which return things like Image objects, Visibility objects, FlowDocuments, etc. to be used on the view, instead of using converters at all?

(在看到

(I came upon these questions after seeing the use of Converters in the WPF demo application that comes with the MVVM Template Toolkit download, see the "Messenger Sample" after unpacking it.)

推荐答案

除了纯UI任务(例如,例如BooleanToVisibilityConverter)之外,我通常在MVVM中根本不使用转换器.恕我直言,您应该在ContractViewModel中声明类型为CustomerViewModel的Customer属性,而不要使用ContractToCustomerConverter

I usually don't use converters at all in MVVM, except for pure UI tasks (like BooleanToVisibilityConverter for instance). IMHO you should rather declare a Customer property of type CustomerViewModel in your ContractViewModel, rather than use a ContractToCustomerConverter

这篇关于如何在MVVM模式中使用WPF转换器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆