NotificationObject类:
它实现了 InotifyPropertyChanged 接口, WPF 正是基于 PropertyChanged 委托实现绑定的。以后我们在业务需要设计的 ViewModel 派生自该类,例如 StudentViewModel 对于需要绑定的属性ID,调用下面的代码实现(例子):
using System.ComponentModel; namespace MyMvvm { class NotificationObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } class StudentViewModel : NotificationObject { private int id; public int Id { get { return id; } set { id = value; this.RaisePropertyChanged("Id"); } } } }
DelegateCommand 类:
它实现了 ICommand 接口, WPF基于 CanExecute 和 Execute 方法实现命令委托的(声明 ExecuteAction 和 CanExecuteFunc 委托)。以后我们在业务需要设计的ViewModel类中,控件命令可以绑定该委托了,例如:
using System; using System.Windows.Input; namespace MyMvvm { class DelegateCommand : ICommand { public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { if (this.CanExecuteFunc == null) return true; return this.CanExecuteFunc.Invoke(parameter); } public void Execute(object parameter) { this.ExecuteAction?.Invoke(parameter); } public Func<object, bool> CanExecuteFunc { get; set; } public Action<object> ExecuteAction { get; set; } } class StudentViewModel : NotificationObject { private int id; public int Id { get { return id; } set { id = value; this.RaisePropertyChanged("Id"); } } /// <summary> /// 查询学号命令 /// </summary> public DelegateCommand QueryIdCommand { get; set; } public StudentViewModel() { QueryIdCommand = new DelegateCommand(); QueryIdCommand.ExecuteAction += (obj) => { Console.WriteLine(this.Id); }; QueryIdCommand.CanExecuteFunc += (obj) => { return true; }; } } }
有了这两个类,我们可以把开发的中心放在数据和逻辑上,交互上所涉及的“动态更新”、UI升级等等都不需要牵涉ViewModel的改动。除非是Property或者Command的变化(增删改)。