Monday, November 15, 2010

Implementation of the ICommand interface for reuse.

    If you use MVVM (model-view-viewmodel) pattern, the most commonly used mechanism is the binding to action in the View using commands. To assignment the command needed to implement an interface ICommand. It's simple, but it will need to do again and again.

    The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param) invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param)).

    Requires the method to switching event CanExecuteChanged. It is called from the user interface elements for switching the state CanExecute () command.

public class ModelCommand : ICommand
{
    #region Constructors

    public ModelCommand(Action<object> execute)
        : this(execute, null) { }

    public ModelCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return _canExecute != null ? _canExecute(parameter) : true;
    }

    public void Execute(object parameter)
    {
        if (_execute != null)
            _execute(parameter);
    }

    public void OnCanExecuteChanged()
    {
        CanExecuteChanged(this, EventArgs.Empty);
    }

    #endregion

    private readonly Action<object> _execute = null;
    private readonly Predicate<object> _canExecute = null;
}

2 comments: