理解MVVM模式

1、WPF的核心是数据绑定。

2、考虑这样一个场景:界面上有一个TextBox显示Person的年龄,一个Button,点击一次Button,年龄加1。

3、做一个View,上面有TextBox和Button,TextBox的Text绑定ViewModel中Person的年龄,Button的Command绑定ViewModel中的命令。

4、设置View的DataContext为ViewModel

5、ViewModel关联Person和Command对象,这里的Person就是Model。ViewModel对View暴露两个接口:Person的Age和Command。

6、Command封装Person的方法,用以改变Person的年龄。

7、Person对ViewModel暴露两个接口:Age属性和AddAge()方法。

8、ViewModel中的Command要实现接口ICommand。

9、Person要实现INotifyPropertyChanged接口或者继承DependencyObject,才能具备自动更新UI的能力。

10、总结:Model对ViewModel暴露属性和方法,方法改变自身的属性值;ViewModel对View暴露Model的属性和Command,Command封装Model的方法;View的DataContext设置为ViewModel,View中的控件绑定ViewModel暴露的Model属性和Command。

11、ViewModel与View是一对多的关系。

12、ViewModel的作用是对View和Model解耦,使View间接关联Model,Model不知道ViewModel的存在,ViewModel不知道View的存在。也就是说,View单向关联ViewModel,ViewModel单向关联Model。

posted on 2013-10-25 18:55  Andy Niu  阅读(319)  评论(0编辑  收藏  举报