c# - MVVM - 模型或 ViewModel 中的 PropertyChanged?

标签 c# mvvm

我已经阅读了一些 MVVM 教程,并且看到了这两种方法。大多数使用 ViewModel for PropertyChanged(这是我一直在做的),但我遇到了一个在模型中这样做的人。这两种方法都可以接受吗?如果是这样,不同方法的优点/缺点是什么?

最佳答案

Microsoft 的 Patterns and Practices,MVVM 的发明者,我都不同意选择的答案。

Typically, the model implements the facilities that make it easy to bind to the view. This usually means it supports property and collection changed notification through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. Models classes that represent collections of objects typically derive from the ObservableCollection class, which provides an implementation of the INotifyCollectionChanged interface.

-- Microsoft 模式和实践:http://msdn.microsoft.com/en-us/library/gg405484%28v=pandp.40%29.aspx#sec4

At this point data binding comes into play. In simple examples, the View is data bound directly to the Model. Parts of the Model are simply displayed in the view by one-way data binding. Other parts of the model can be edited by directly binding controls two-way to the data. For example, a boolean in the Model can be data bound to a CheckBox, or a string field to a TextBox.

-- MVVM 的发明者 John Gossman:http://blogs.msdn.com/b/johngossman/archive/2005/10/08/478683.aspx

我自己的文章:http://www.infoq.com/articles/View-Model-Definition


拥有一个仅包装模型并公开相同属性列表的“ View 模型”是一种反模式。 View 模型的工作是调用外部服务并公开这些服务返回的个体和模型集合。

原因:

  1. 如果直接更新模型, View 模型将不知道触发属性更改事件。这会导致 UI 不同步。
  2. 这严重限制了您在父 View 模型和 subview 模型之间发送消息的选项。
  3. 如果模型有自己的属性更改通知,#1 和 2 不是问题。相反,如果包装 VM 超出范围但模型没有超出范围,则您必须担心内存泄漏。
  4. 如果您的模型很复杂,有很多子对象,那么您必须遍历整个树并创建第二个对象图来覆盖第一个对象图。这可能非常乏味且容易出错。
  5. 包装集合尤其难以使用。任何时候(UI 或后端)从集合中插入或删除项目时,影子集合都需要更新以匹配。这种代码真的很难写对。

这并不是说您永远不需要包装模型的 View 模型。如果您的 View 模型公开的属性与模型明显不同,并且不能仅用 IValueConverter 覆盖,那么包装 View 模型就有意义了。

您可能需要包装 View 模型的另一个原因是您的数据类出于某种原因不支持数据绑定(bind)。但即便如此,通常最好只创建一个普通的、可绑定(bind)的模型并从原始数据类中复制数据。

当然,您的 View 模型将具有特定于 UI 的属性,例如当前选择了集合中的哪个项目。

关于c# - MVVM - 模型或 ViewModel 中的 PropertyChanged?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16864610/

相关文章:

c# - 以编程方式检查 Windows 服务是否正在运行 C#

mvvm - 剑道用户界面 : How to set the value of a tooltip with a MVVM binding

silverlight - WP7 SL - 如何在一个 View 中使用两个不同的 View 模型。一个 VM : Display, 其他用于用户输入并对其进行操作

c# - 将文本附加到富文本框的最快方法?

Android MVVM 设计模式

c# - 我应该如何在 ViewModel 之间进行通信?

c# - 如何在没有模式的情况下将源 MediaCapture 绑定(bind)到 CaptureElement?

c# - WPF UI 线程被大集合阻塞

c# - 我如何根据大型值数据库解析自由文本(Twitter 推文)?

c# - 如何在 Visual Studio 2017 项目(新的 .csproj 文件格式)中设置 `OutputPath` 而目标框架不会混淆已解析的路径?