WPF简单MVVM实现
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 }
3.2.接着要创建DelegateCommand,实现了ICommand接口,用来处理View发送到ViewModel的命令,代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows.Input; 7 8 namespace MVVMTest.Commands 9 { 10 public class DelegateCommand:ICommand 11 { 12 public bool CanExecute(object parameter) 13 { 14 if (this.CanExecuteFunc == null) 15 { 16 return true; 17 } 18 19 return this.CanExecuteFunc(parameter); 20 } 21 22 public event EventHandler CanExecuteChanged; 23 24 public void Execute(object parameter) 25 { 26 if (this.ExecuteAction == null) 27 { 28 return; 29 } 30 this.ExecuteAction(parameter); 31 } 32 33 public Action<object> ExecuteAction { get; set; } 34 public Func<object, bool> CanExecuteFunc { get; set; } 35 } 36 }