Simplifying RelayCommand/DelegateCommand in WPF MVVM ViewModels Simplifying RelayCommand/DelegateCommand in WPF MVVM ViewModels wpf wpf

Simplifying RelayCommand/DelegateCommand in WPF MVVM ViewModels


This is exactly the same as if you would offer a - say integer - property that calculates some constant value.You can either calculate it for each call on the get-method or you can create it on the first call and then cache it, in order to return the cached value for later calls.So if the getter is called at most once, it does make no difference at all, if it is called often, you will lose some (not much) performance, but you won't get real trouble.

I personally like to abbreviate the MSDN-way like this:

RelayCommand _saveCommand;public ICommand SaveCommand{  get  {    return _saveCommand ?? (_saveCommand = new RelayCommand(param => this.Save(),                                                            param => this.CanSave ));  }}


I discovered that you need the original way from MSDN if you have multiple controls that invoke the same commands, otherwise each control will new its own RelayCommand. I didn't realize this because my app only has one control per command.

So to simplify the code in ViewModels, I'll create a command wrapper class that stores (and lazily instantiates) all the RelayCommands and throw it in my ViewModelBase class. This way users do not have to directly instantiate RelayCommand or DelegateCommand objects and don't need to know anything about them:

    /// <summary>    /// Wrapper for command objects, created for convenience to simplify ViewModel code    /// </summary>    /// <author>Ben Schoepke</author>    public class CommandWrapper    {    private readonly List<DelegateCommand<object>> _commands; // cache all commands as needed    /// <summary>    /// </summary>    public CommandWrapper()    {        _commands = new List<DelegateCommand<object>>();    }    /// <summary>    /// Returns the ICommand object that contains the given delegates    /// </summary>    /// <param name="executeMethod">Defines the method to be called when the command is invoked</param>    /// <param name="canExecuteMethod">Defines the method that determines whether the command can execute in its current state.    /// Pass null if the command should always be executed.</param>    /// <returns>The ICommand object that contains the given delegates</returns>    /// <author>Ben Schoepke</author>    public ICommand GetCommand(Action<object> executeMethod, Predicate<object> canExecuteMethod)    {        // Search for command in list of commands        var command = (_commands.Where(                            cachedCommand => cachedCommand.ExecuteMethod.Equals(executeMethod) &&                                             cachedCommand.CanExecuteMethod.Equals(canExecuteMethod)))                                             .FirstOrDefault();        // If command is found, return it        if (command != null)        {            return command;        }        // If command is not found, add it to the list        command = new DelegateCommand<object>(executeMethod, canExecuteMethod);        _commands.Add(command);        return command;    }}

This class is also lazily instantiated by the ViewModelBase class, so ViewModels that do not have any commands will avoid the extra allocations.


One thing that I do is let Visual Studio do the typing for me. I just created a code snippet that allows me to create a RelayCommand by typing

rc Tab Save Enter

rc is the code snippet shortcuttab loads the text you type what you want and it creates all the other wording.

Once you look at one code snippet and create your own you'll never go back :)

For more information on creating code snippets: http://msdn.microsoft.com/en-us/library/ms165394.aspx