开发者

The role of the model in MVVM

开发者 https://www.devze.com 2023-02-10 20:28 出处:网络
I\'ve read a few articles regarding the role of the (Data)Model in the MV开发者_高级运维VM pattern.

I've read a few articles regarding the role of the (Data)Model in the MV开发者_高级运维VM pattern. However, i still could not figure what goes into the model.

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

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?

Thank you very much!


The model implements your business logic. The view model decorates your business logic for the purpose of displaying it and interacting with it, in a view (UI of some form, eg. web, winform, CLI). So, no, I would not say that your model should implement INotifyPropertyChanged unless it would do so as part of your core business logic.


From one of your comments:

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

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.

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."

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.


In some cases a Model must implement INotifyPropertyChanged. Imagine that you are coding client for ICQ or something like that. How is the ViewModel supposed to know, that somebody send you a message?

Difference between Model and ViewModel:

A ViewModel only simplifies the output from a Model. If the model is very simple, a ViewModel isn't necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消