命令基本元素及关系
WPF里已经有了路由事件,那为何还须要命令呢?
由于事件指负责发送消息,对消息如何处理则无论,而命令是有约束力,每一个接收者对命令执行统一的行为,好比菜单上的保存,工具栏上的保存都必须是执行一样的保存。
WPF命令必需要实现ICommand接口,如下为ICommand接口结构工具
using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Markup; namespace System.Windows.Input { public interface ICommand { //摘要:当出现影响是否应执行该命令的更改时发生。 event EventHandler CanExecuteChanged; //摘要:定义用于肯定此命令是否能够在其当前状态下执行的方法。 //参数:此命令使用的数据。 若是此命令不须要传递数据,则该对象能够设置为 null。 //返回结果:若是能够执行此命令,则为 true;不然为 false。 bool CanExecute(object parameter); //摘要:定义在调用此命令时调用的方法。 //参数:此命令使用的数据。 若是此命令不须要传递数据,则该对象能够设置为 null。 void Execute(object parameter); } }
ICommand接口实现this
using System; using System.Windows.Input; namespace Micro.ViewModel { public class DelegateCommand : ICommand { public Action<object> ExecuteCommand = null; public Func<object, bool> CanExecuteCommand = null; public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { if (CanExecuteCommand != null) { return this.CanExecuteCommand(parameter); } else { return true; } } public void Execute(object parameter) { if (ExecuteCommand != null) this.ExecuteCommand(parameter); } public void RaiseCanExecuteChanged() { CanExecuteChanged?.Invoke(this, EventArgs.Empty); } } }