命令基本元素及關係
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); } } }