您的ViewModel是否应该将XAML元素公开为属性? [英] Should your ViewModel expose XAML elements as properties or not?

查看:89
本文介绍了您的ViewModel是否应该将XAML元素公开为属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在StackOverflow问题上结束 如何在MVVM模式中使用WPF转换器? 我了解到,不应在MVVM模式中使用值转换器,因为值转换器的功能应由ViewModel本身.

Over at the StackOverflow question How can WPF Converters be used in an MVVM pattern? I've learned that Value Converters should not be used in the MVVM pattern since the functionality of a Value Converter should be handled by the ViewModel itself.

这很有道理.

但是我记得读过,您不应该不向视图公开XAML元素,而应仅公开视图然后使用DataTemplates绑定和显示的数据集合.

But I remember reading that you should not expose XAML elements to the View, but instead expose only collections of data which the View then binds and displays using DataTemplates.

但是,转换器似乎功能非常强大(例如,如在 MVVM模板演示,请解压缩后查看"Messenger示例",因为它们可以将对象转换为对象,例如消息对象到FlowDocument对象,客户对象到可见性对象,自定义状态对象到图像等.

However, converters seem quite powerful (e.g. as they are used in the MVVM Template demo, see the "Messenger Sample" after unpacking it) in that they can convert objects to objects, e.g. Message objects to FlowDocument objects, or Customer objects into Visibility objects, or custom Status objects into Images, etc.

因此,如果ViewModel要采用Value Converter的功能,则必须公开XAML元素和属性,例如StackPanel,Visibility,Color,FlowDocument等,正确的?

So if a ViewModel is going to take on the functionality of a Value Converter, it is going to have to expose XAML elements and properties such as StackPanel, Visibility, Color, FlowDocument, etc., right?

有人看到ViewModel不应该像Value Converter那样公开这些丰富的XAML对象的任何原因吗?

推荐答案

因为这将ViewModel限制为只能用于特定的视觉表示. 一旦您拥有发出XAML的ViewModel,它就会将设计内容放入开发人员的域中. 这意味着使用Expression Blend的设计人员无法编辑设计资产-设计人员/开发人员的工作流程已损坏. 将XAML保留在页面上,并将值转换器与数据模板一起使用,可使设计与代码分离.

Because then that limits the ViewModel to be used only with a specific visual representation. Once you have the ViewModel emitting XAML, it puts design content into a developer's domain. This means that the designer using Expression Blend cannot edit design assets - and the designer/developer workflow is broken. Keeping the XAML on the page and using Value converters with data templating keeps the design separated from the code.

当您的ViewModel公开特定的XAML时,它还限制了该ViewModel仅在该特定实例中使用,并且使其重用性降低.

When your ViewModel exposes specific XAML it also limits that ViewModel to be used only in that specific instance and makes it less reusable.

这篇关于您的ViewModel是否应该将XAML元素公开为属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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