MVVM旨在数据驱动,通过绑定的模式实现前后端交互。最重要的就是属性更改时的通知功能以及命令(Command)的绑定。
一、定义通知类(BindableBase)
Prism框架有个BindableBase的基类,可以实现属性更改后通知前端。这里实现一个类似的BindableBase类。
首先继承INotifyPropertyChanged接口,并对事件PropertyChanged调用即可。
public class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisedPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
}
}
二、定义Command类(DelegateCommand)
类似Prism框架里的DelegateCommand,简单实现其功能,但和Prism差很多,Prism扩展功能要多很多。
DelegateCommand继承ICommand接口,并实现接口的CanExecute、Execute方法;
public class DelegateCommand<T> : ICommand
{
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<T> execute, Func<T, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if(_canExecute == null)
{
return true;
}
return _canExecute((T)parameter);
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
private Action<T> _execute;
private Func<T, bool> _canExecute;
}