为什么模型中有 ObservableCollection 和 INotifyPropertyChanged ?
我在 msdn 上读到MVVM 中的模型通常会实现 ObservableCollectionINotifyPropertyChanged
等接口, IDataError
。
我的问题是为什么这是在模型级别而不是 ViewModel 级别完成的。我希望“纯”模型不会有任何通知逻辑,只有数据和业务逻辑。我的第一印象是虚拟机将包装模型的属性并处理通知。
我欣然承认,在模型中实现这些接口可能会使在许多情况下实现更容易,但我正在寻找关于为什么模型应该负责通知的解释。
I've read on msdn that it is common for Models in MVVM to implement interfaces such as ObservableCollection<T>
, INotifyPropertyChanged
, and IDataError
.
My question is around why this is done at the model level and not the ViewModel level. I would expect that a "pure" Model would not have any notification logic, just data and business logic. My first impression is that the VM would wrap the Model's properties and take care of the notifications.
I readily admit that implementing these interfaces in the Model may make implementation easier in many cases, but I'm looking for an explanation as to why the model should be responsible for notifications.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
INPC 是核心框架的一部分,与专门属于 WPF 的 ICommand 和 DependencyObject 不同。关于从服务层公开 IQueryable 有一个类似的问题。就像 INPC 一样,IQueryable 是一个核心框架类。不使用它们中的任何一个来创建纯模型都是矫枉过正的。
更糟糕的是,它会导致重复(使 VM 包装公开属性只是为了添加属性更改通知)。
另一方面,Observable Collection 是一个不同的野兽。通常,领域模型中的集合表示实体关系。在许多情况下,您无法控制它们的实例化。那里需要做出权衡
INPC is part of the Core framework unlike say ICommand and DependencyObject which belong to WPF specifically. There was a similar question regarding exposing IQueryable from the service layer. Just like INPC, IQueryable is a core framework class. Not using either of them in an effort to create a pure model is overkill.
Even worse it causes duplication (making the VM wrap expose properties just to add a propertychanged notification).
Observable Collection on the other hand is a different beast. Usually collections in a domain model represent entity relations. In many cases, you don't have control over their instantiation. There's a tradeoff to be made there
根据您的应用程序,您可能拥有相同数据的多个视图和视图模型。假设您有一个窗口显示带有只读详细信息的项目列表,但在另一个窗口中您可以添加、编辑和删除项目。
如果模型使用
ObservableCollection
和INotifyPropertyChanged
,则可编辑 View/ViewModel 中所做的更改将在不可编辑 View/ViewModel 中看到并更新。此外,如果不可编辑的视图足够简单,则简单地公开并直接绑定到模型是可能且可接受的。由于没有 ViewModel 来处理通知,因此模型需要自己完成这项工作。
Depending on your application, you might have multiple Views and ViewModels of the same data. Say you have one window that shows a list of items with read-only details, but in another window you have the ability to add, edit, and remove items.
If the Model uses
ObservableCollection
andINotifyPropertyChanged
, the changes made in the editable View/ViewModel will be seen and updated in the non-editable View/ViewModel.Furthermore, if the non-editable View is simple enough, it can be possible and acceptable to simply expose and bind directly to the model. As there is no ViewModel to handle the notification, the Model would need to do the job itself.