wpfmvvmdelegatecommand

How can I simplify the implementation of Commands in ViewModels for WPF/MVVM?


I have noticed that I am repeating a lot of code when implementing Commands on ViewModels for a MVVM-WPF scenario. The standard implementation, as shown below, consists of a public readonly field of type ICommand, a private DelegateCommand field and a method for the execution logic. DelegateCommand gets initialized in the ICommands get-accessor.

How can this approach be condensed, considering the repetition for every command?

private DelegateCommand saveCommand;
private DelegateCommand commandClearInputFileList;
private DelegateCommand commandInputFilesDeleteSelected;

public ICommand SaveCommand {
    get {
        if (saveCommand == null) {
            saveCommand = new DelegateCommand(CommitDataBasePush);
        }
        return saveCommand;
    }
}

public ICommand CommandClearInputFileList {
    get {
        if (commandClearInputFileList == null) {
            commandClearInputFileList = new DelegateCommand(InputFilesClear);
        }
        return commandClearInputFileList;
    }
}

public ICommand CommandInputFilesDeleteSelected {
    get {
        if (commandInputFilesDeleteSelected == null) {
            commandInputFilesDeleteSelected = new DelegateCommand(InputFilesDeleteSelected);
        }
        return commandInputFilesDeleteSelected;
    }
}

Solution

  • In addition to the null coalescing operator, you can use Lazy Loading:

    private Lazy<DelegateCommand> _cmd = new Lazy<DelegateCommand>(() => new DelegateCommand(InputFilesClear) );
    
    public ICommand CommandClearInputFileList { get { return _cmd.Value; } }
    

    Personally, I've moved away from commands in favor of the conventions provided by Caliburn.Micro framework. The command above would simply be replaced by a public method.