Tuesday, 16 July 2013

WPF How to implement a reusable ICommand



If you are using the MVVM (model-view-viewmodel) pattern, one of the most used mechanisms to bind actions to the view is 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, when ICommand.Execute(object param) is invoked, and one that evalues the state of the command when ICommand.CanExecute(object param) is called.
In addition to this, we need a method, which triggers the CanExecuteChanged event. This causes the UI element to reevaluate the CanExecute() of the commmand.
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);
        }
    }
}

No comments:

Post a Comment