Bookmark and Share Share...    Subscribe to this feed Feed   About me...


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, 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, 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);
        }
    }
}
 
 
 
 



 Comments on this article

Show all comments
lan
Commented on 19.April 2010
Good artical!
If with an example is better
YJ
Commented on 12.May 2010
If you want an example, check http://www.codeproject.com/KB/WPF/MVVMForDummies.aspx
A lot simple, but it could help.
Ganesh
Commented on 20.August 2010
Good artical!

but no any example need eample for all property as like your wcf article
C-MOSE
Commented on 23.August 2010
I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this from another website

Name
E-Mail (optional)
Comment
About Christian Moser