ICommand接口
一、DelegateCommand<T>(推荐)
public class DelegateCommand : ICommand { public event EventHandler CanExecuteChanged; private Action action; public DelegateCommand(Action action) { this.action = action; } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { action?.Invoke(); } } public class DelegateCommand<T> : ICommand { public event EventHandler CanExecuteChanged; private Action<T> action; public DelegateCommand(Action<T> action) { this.action = action; } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { action?.Invoke((T)parameter); } }
二、Action<object>
public class MyCommand : ICommand { public event EventHandler CanExecuteChanged; private Action action; private Action<object> objectAction; public MyCommand(Action action) { this.action = action; } public MyCommand(Action<object> objectAction) { this.objectAction = objectAction; } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { action?.Invoke(); objectAction?.Invoke(parameter); } }