MVVM Light: RelayCommand: define it lazy or in the constructor?

There are several examples of how to define RelayCommand in a ViewModel :

Option 1 ( lazy ):

/// <summary> /// Gets the LogOnCommand. /// </summary> /// <value>The LogOnCommand.</value> public RelayCommand<LogOnUser> LogOnCommand { get { if (this.logOnCommand == null) { this.logOnCommand = new RelayCommand<LogOnUser>( action => { // Action code... }, g => g != null); } return this.logOnCommand; } } 

Option 2 (in the constructor )

 /// <summary> /// Initializes a new instance of the <see cref="LogOnFormViewModel"/> class. /// </summary> public LogOnFormViewModel() { this.logOnCommand = new RelayCommand<LogOnUser>( action => { // Action code... }, g => g != null); } /// <summary> /// Gets the LogOnCommand. /// </summary> /// <value>The LogOnCommand.</value> public RelayCommand<LogOnUser> LogOnCommand {get; private set;} 

What is the best / clear design?

+4
source share
1 answer

It depends on which style you prefer. Most people do not like to have a bunch of logic in properties if they can avoid it.

Personally, I prefer to have a real method to call instead of an anonymous method. My ViewModels look something like this.

 public class MyViewModel : ViewModelBase { public RelayCommand<CommandParam> MyCommand { get; private get; } public MyViewModel() { CreateCommands(); } private void CreateCommands() { MyCommand = new RelayCommand<CommandParam>(MyCommandExecute); } private void MyCommandExecute(CommandParam parm) { // Action code... } } 

Note: if you do not use the enable command, you do not need to invoke the ctor overload, which sets this.

+10
source

All Articles