MVVM 与 Silverlight
我下载了很多示例代码来帮助我更好地理解 silverlight 中的 MVVM。
我注意到的一件事是我下载的示例代码中存在不一致。例如,有些在视图模型上实现 INotifyPropertyChanged,而另一些则在模型上实现。
哪种是处理属性更改的首选方式,应该在模型级别还是视图模型级别处理?
I have been downloading a lot of example code to help me gain a better understanding of MVVM within silverlight.
One of the things I have noticed is an inconsistency within the sample code I have downloaded. Some for example implement INotifyPropertyChanged on the viewmodels, where others implement it on the Model.
Which is the preferred way of handling property changes, should it be handled at the model level or the viewmodel level?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果要通过数据绑定更新视图中显示的项目,则处理(通知)视图模型中的属性更改似乎更自然。
首先拥有视图模型的原因之一是它以一种易于视图绑定到模型的方式保存模型中的数据。
因此,如果 INotifyPropertyChange 的主要原因是更新视图中绑定的项目,则应该在视图模型中更新它。
Handling (Notifying) property changes in the viewmodel would seem more natural if this is to update the item that's being displayed in the view by databinding.
One of the reasons for having a viewmodel in the first place is that it holds the data from the model in such a way that it's easy for the view to bind to it.
So, if the main reason for your INotifyPropertyChange in is to update the item which is bound in the view, you should update it in the viewmodel.
我通常使用
DependencyProperty
而不是INotifyPropertyChanged
,但想法是相同的。它们的目的是通知它们所绑定的视图控件它们已发生更改,以便视图可以更新。这意味着视图与拥有属性或对象的任何内容之间的联系很弱。在 MVVM 中,由于关注点分离,视图永远不应该与模型有任何链接。
我经常会通过为每个视图、视图模型和模型创建一个单独的项目来强制执行此操作。因此,您问题的答案是 INotifyPropertyChanged 应该在视图模型级别实现,因为视图永远不应该接触模型级别的任何内容。话虽如此,MVVM 只是一种使程序员的工作更轻松的编码范例,因此如果这意味着让您的工作更轻松并且不会产生任何负面后果,那么可能有理由以不同的方式实现它。
I typically use
DependencyProperty
instead ofINotifyPropertyChanged
, but the idea is the same.Their purpose is to notify the view controls, they are bound to, that they have changed so the view can update. This implies a weak connection between the view and whatever holds the property or object. In MVVM, the view should never have any link to the model because of separation of concerns.
I will often have physically force this by creating a separate project for each of the view, viewmodel, and model. So, the answer to your question is that the
INotifyPropertyChanged
should be implemented at the viewmodel level because the view should never touch anything from the model level. Having said this, MVVM is just a coding paradigm to make the programmers job easier, so there could be reasons to implement it differently if it means making your job easier and it doesn't having any negative consequences.