Why have ObservableCollection and INotifyPropertyChanged in Model?
I've read on msdn that it is common for Models in MVVM to implement interfaces such as ObservableColl开发者_如何学编程ection<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.
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
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
and INotifyPropertyChanged
, 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.
精彩评论