WPF View与ViewModel的交互
1.WPF中的View 即视图,用来显示的界面,可能是一个窗体,一个对话框等。
2.WPF中的ViewModel 即与View对应的视图模型,用来完成底部的数据操作与更新View显示。
3.初步实现逻辑
a.继承INotifyPropertyChanged接口,实现组件属性更改时引发的PropertyChangedEventHandler事件
class NotificationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
b.在ViewModel中继承NotificationObject类,定义需要的字段与属性,当属性值更改时实现值的传递
private double input1;
public double Input1
{
get { return input1; }
set
{
input1 = value;
this.RaisePropertyChanged("Input1");
}
}
c.定义DelegateCommand类继承ICommand接口,实现接口的方法
class DelegateCommand : ICommand
{
public bool CanExecute(object parameter)
{
if (this.CanExecuteFunc == null)
return true;
return this.CanExecuteFunc(parameter);
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (this.ExecuteAction == null)
return;
this.ExecuteAction(parameter);
}
public Action<object> ExecuteAction { get; set; }
public Func<object,bool> CanExecuteFunc { get; set; }
}
d.在ViewModel中实现需要的逻辑方法
public DelegateCommand AddCommand { get; set; }
private void Add(object parameter)
{
this.Result = this.Input1 + this.Input2;
}
public MainWindowViewModel()
{
this.AddCommand = new DelegateCommand();
this.AddCommand.ExecuteAction = new Action<object>(this.Add);
}
4.最后,在View中添加控件的绑定,实现交互
this.DataContext = new MainWindowViewModel();
<Button x:Name="addButton" Command="{Binding AddCommand}"/>