为什么某些ViewModels实现INotifyPropertyChanged? [英] Why do some ViewModels implement INotifyPropertyChanged?

查看:327
本文介绍了为什么某些ViewModels实现INotifyPropertyChanged?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑.主要是关于如何分隔代码以及如何在每个类中正确放置代码.我特别注意到一些示例,ViewModel类实现了INotifyPropertyChanged,并且它们具有引发PropertyChanged的属性. 事件.但是,根据其他示例,这看起来应该在Model类中.同样在 " 实现模型在MSDN上的Windows Phone应用示例中找到-View-ViewModel模式" ,则ViewModel类未实现INotifyPropertyChanged.

I'm kind of confused. Mostly about how to separate my code and correct placement of code within each class.  In particular I noticed that some examples, the ViewModel class implements INotifyPropertyChanged and they have properties that raise PropertyChanged event.  But this looks like what should go in the Model class according to other examples.  Also in the "Implementing the Model-View-ViewModel pattern in a Windows Phone app" example on MSDN, the ViewModel class doesn't implement INotifyPropertyChanged.  Can someone please explain? 

推荐答案

INotifyPropertyChanged和INotifyPropertyChanging应该进入视图模型,除非有理由将它们放入模型中.您不想不必要地污染模型.但是,在许多示例和应用程序中,模型和视图模型是 由同一班代表.对于简单模型,通常是这种情况.

INotifyPropertyChanged and INotifyPropertyChanging should go into the view model unless there are reasons to put them in the model. You don't want to pollute your models unnecessarily. In many examples and applications, however, models and view models are represented by the same class. This will often be the case for simple models.

问问自己:在这种特殊情况下,分离模型和查看模型会带来什么改进?区别仅限于INotifyPropertyChanged-其余代码将按1:1复制.代码重复是经典的代码味道 以及正确应用MVVM模式的副作用.但是,只有在必要时才应引入这种复杂性.

Ask yourself: What improvement would it bring to separate model and view model in this particular case? The difference would be limited to INotifyPropertyChanged - the rest of the code would be duplicated 1:1. Duplication of code is a classic code smell AND a side effect of proper application of the MVVM pattern. But you should introduce such complexity only if necessary.

关于示例中与视图模型类有关的问题,由于ObservableCollection< Accomplishment>可以实现INotifyPropertyChanged的间接实现.公开INotifyCollectionChanged(与集合基本相同).

As for your question concerning the view model class in the example, INotifyPropertyChanged is implemented indirectly because the ObservableCollection<Accomplishment> exposes INotifyCollectionChanged (which is basically the same for collections).


这篇关于为什么某些ViewModels实现INotifyPropertyChanged?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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