How to implement a reusable ICommand
Introduction
If you are using the MVVM (model-view-viewmodel) pattern, one of the most used mechanism to bind actions to the view are commands. To provide a command, you have to implement the ICommand
interface. This is quite simple, but you have to do it over and over again. This is cumbersome.
The idea of this pattern build an universal command, that takes two delegates: One that is called, whenICommand.Execute(object param)
is invoked, and one that evalues the state of the command whenICommand.CanExecute(object param)
is called.
In addition to this, we need a method, that triggers the CanExecuteChanged
event. This causes the ui element to reevaluate the CanExecute()
of the commmand.
Sample implementation
public class DelegateCommand : ICommand { private readonly Predicate<object> _canExecute; private readonly Action<object> _execute; public event EventHandler CanExecuteChanged; public DelegateCommand(Action<object> execute) : this(execute, null) { } public DelegateCommand(Action<object> execute, Predicate<object> canExecute) { _execute = execute; _canExecute = canExecute; } public override bool CanExecute(object parameter) { if (_canExecute == null) { return true; } return _canExecute(parameter); } public override void Execute(object parameter) { _execute(parameter); } public void RaiseCanExecuteChanged() { if( CanExecuteChanged != null ) { CanExecuteChanged(this, EventArgs.Empty); } } }