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 ICommand
s 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;
}
}