Custom Relay command for ICommands

I always find working with a custom RelayCommand object of type ICommand lot more convenient that directly declaring Command objects of type ICommand in my ViewModel.

I created a RelayCommand class and then used that in all my viewmodels. Using lamba expression, i can then direct the execute method of ICommand directly inside the same viewmodel, which is lot more readable then having excecute methods in seperate ICommand implmentations

Here is how i do define relay command:

public class RelayCommand : ICommand
#region Fields

readonly Action<object> _execute;
readonly Predicate<object> _canExecute;

#endregion // Fields

#region Constructors

/// <summary>
/// Creates a new command that can always execute.
/// </summary>
/// <param name=”execute”>The execution logic.</param>
public RelayCommand(Action<object> execute)
: this(execute, null)

/// <summary>
/// Creates a new command.
/// </summary>
/// <param name=”execute”>The execution logic.</param>
/// <param name=”canExecute”>The execution status logic.</param>
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
if (execute == null)
throw new ArgumentNullException(“execute”);

_execute = execute;
_canExecute = canExecute;

#endregion // Constructors

#region ICommand Members

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

public event EventHandler CanExecuteChanged
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }

public void Execute(object parameter)

#endregion // ICommand Members

Then i can just use this RelayCommand in my ViewModel to expose my ViewModel commands as follow:

public ICommand DoWorkCommand
get { return new RelayCommand(param => DoWork(),x=>!booleanflag); }

The DoWork() methods is defined locally so is the booleanflag.

This style of using Command makes if very convenient when you have many commands on your WPF page.

Have a good day!

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s