继承ICommand ,RelayCommand命令
1 public class RelayCommand : ICommand 2 { 3 private readonly Action _execute; 4 private readonly Func<bool> _canExecute; 5 public event EventHandler CanExecuteChanged; 6 public RelayCommand(Action execute) : this(execute, null) 7 { 8 } 9 public RelayCommand(Action execute, Func<bool> canExecute) 10 { 11 if (execute == null) 12 { 13 throw new ArgumentNullException("execute"); 14 } 15 this._execute = execute; 16 this._canExecute = canExecute; 17 } 18 public void RaiseCanExecuteChanged() 19 { 20 EventHandler canExecuteChanged = this.CanExecuteChanged; 21 if (canExecuteChanged != null) 22 { 23 canExecuteChanged.Invoke(this, EventArgs.Empty); 24 } 25 } 26 [DebuggerStepThrough] 27 public bool CanExecute(object parameter) 28 { 29 return this._canExecute == null || this._canExecute.Invoke(); 30 } 31 public void Execute(object parameter) 32 { 33 this._execute.Invoke(); 34 } 35 }
我们改变SaveCommand的CanExecute从false到true,而save命令执行的状态。CanExecuteChanged事件和客户端调用CanExecute方法,.在实践中,这将使一个“保存”按钮,该按钮被绑定到SaveCommand改变它的状态从禁用和重新启用。
1 public class BlingViewModel 2 { 3 private DelegateCommand<object> _saveCommand; 4 private bool _canSaveExecute = true; 5 public ICommand SaveCommand 6 { 7 get 8 { 9 if (_saveCommand == null) 10 { 11 _saveCommand = new DelegateCommand<object>(executeMethod: _ => Save(), canExecuteMethod: _ => _canSaveExecute); 12 } 13 return _saveCommand; 14 } 15 } 16 private void Save() 17 { 18 _canSaveExecute = false; 19 _saveCommand.RaiseCanExecuteChanged(); 20 Console.WriteLine("Saving..."); 21 _canSaveExecute = true; 22 _saveCommand.RaiseCanExecuteChanged(); 23 } 24 }
.也可以直接调用System.Windows.Input.CommandManager.InvalidateRequerySuggested()让你的
CanExecute
处理程序重新评估。