天天看點

了解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的能力。