理解MVVM模式

Andy Niu發表於2013-10-25

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。

相關文章