在MVVM模型的作用 [英] The role of the model in MVVM

查看:95
本文介绍了在MVVM模型的作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过关于在MVVM模式(数据)示范作用的几篇文章。
但是,我还是想不出什么进入的模式。

I've read a few articles regarding the role of the (Data)Model in the MVVM pattern. However, i still could not figure what goes into the model.

如果模型实现INotifyPropertyChanged?如果是这样,什么是虚拟机和模型之间的区别?

Should the model implement INotifyPropertyChanged? If so, what is difference between the VM and the model?

如果没有,模型不会通知VM并认为它发生的变化。所以 - 考虑逻辑进入模型,它似乎是显而易见的,它应该通知视图模型有关它的一些变化。然而,是不是很奇怪在这两个类实现INotifyPropertyChanged?

If not, a change in the Model will not notify the VM and the View that it occured. So - considering the logic goes into the Model, it seems obvious that it should notify the ViewModel about some of it's changes. However, isn't it weird to implement INotifyPropertyChanged in both classes?

非常感谢你!

推荐答案

从您的意见之一:

这似乎不可思议,我认为该模型实现INotifyPropertyChanged,这似乎我作为一个UI相关的类

it seems weird to me that the model implements INotifyPropertyChanged, which seems to me as a UI-Related class

更改通知在各种环境中使用,只是没有UI上下文。例如,您可能要附上一段诊断代码,记录具体更改为的TextWriter 。如果对象实现改变通知这很容易不加修改实现到底层模型对象

Change notification's used in all kinds of contexts, just not UI contexts. For instance, you might want to attach a piece of diagnostic code that logs specific changes to a TextWriter. This is easily accomplished without modification to the underlying model object if the object implements change notification.

但是,即使在它仅被用于更新UI的应用程序,这种模式仍然是有意义的。由于更改通知通过事件的处理,提高了事件的对象是从处理它的对象脱钩。您的模型不知道,也不需要知道,什么样的用户界面在使用它。它只是说,假设有一个UI,我需要告诉它,不管它是什么,这个属性的值只是改变了。

But even in an application where it's only being used to update the UI, this pattern still makes sense. Because change notification is handled through an event, the object raising the event is decoupled from the object handling it. Your model doesn't know, and doesn't need to know, what kind of UI is using it. It's just saying, "Assuming that there's a UI, I need to tell it, whatever it is, that this property's value just changed."

那么,为什么会出现一个视图模型?为什么不直接绑定到该模型直接?事实上,你的可以的只是绑定到直接模式如果实现更改通知。在很多简单的WPF应用程序,但并不需要是一个独立的视图模型 - 你可以执行变更通知,并在模型和收工。这是当你需要从底层业务逻辑中分离的用户界面,你就会开始被关注与否您违反了单一职责原则,即需要一个浏览模式出现。

So why is there a view model? Why not just bind to the model directly? In fact, you can just bind to the model directly if it implements change notification. In a lot of simple WPF applications, there doesn't need to be a separate view model - you can just implement change notification in the model and call it a day. It's when you need to decouple the UI from the underlying business logic and you start being concerned about whether or not you're violating the single-responsibility principle that the need for a view model arises.

这篇关于在MVVM模型的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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