1. MVVM介绍:
MVVM就是: Model -- 模型(现实中对象的抽象)
View -- UI(用户界面)
ViewModel -- UI界面的抽象(给View提供数据,并响应View的操作)
2. 关键是要能准确的进行ViewModel的建模,处理好View与ViewModel之间的关系
2.1. 只有2种关系:
数据传递 --- 双向,使用Binding实现;
操作传递 --- 单向(只从View传递给ViewModel),使用命令Command实现;
3. 开始
3.1. 首先创建NotificationObject,它是所以ViewModel的基类
因为要使用Binding,而ViewModel就充当数据源的角色,而要实现当值有变化时会自动响应,就必须实现INotifyPropertyChanged接口,代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace MVVMTest.ViewModels 9 { 10 public class NotificationObject:INotifyPropertyChanged 11 { 12 public event PropertyChangedEventHandler PropertyChanged; 13 14 public void RaisePropertyChanged(string property) 15 { 16 if (this.PropertyChanged != null) 17 this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(property)); 18 19 } 20 } 21 }