Search code examples
c#wpfmvvmrelaycommanddelegatecommand

Simplifying RelayCommand/DelegateCommand in WPF MVVM ViewModels


If you're doing MVVM and using commands, you'll often see ICommand properties on the ViewModel that are backed by private RelayCommand or DelegateCommand fields, like this example from the original MVVM article on MSDN:

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

However, this is a lot of clutter, and makes setting up new commands rather tedious (I work with some veteran WinForms developers who balk at all this typing). So I wanted to simplify it and dug in a little. I set a breakpoint at the first line of the get{} block and saw that it only got hit when my app was first loaded--I can later fire off as many commands as I want and this breakpoint never gets hit--so I wanted to simplify this to remove some clutter from my ViewModels and noticed that the following code works the same:

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

However, I don't know enough about C# or the garbage collector to know if this could cause problems, such as generating excessive garbage in some cases. Will this pose any problems?


Solution

  • 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.