Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

There are several examples on how to define a RelayCommand in the 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 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 / clearest design ?

like image 703
Stef Heyenrath Avatar asked Dec 28 '22 09:12

Stef Heyenrath


1 Answers

It really depends on what style you prefer. Most people don't like having a bunch of logic in property getters if they can avoid it.

Personally, I prefer having 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 set; }

    public MyViewModel()
    {
        CreateCommands();
    }

    private void CreateCommands()
    {
        MyCommand = new RelayCommand<CommandParam>(MyCommandExecute);
    }

    private void MyCommandExecute(CommandParam parm)
    {
        // Action code...
    }
}

Notice that if you're not using the enable command, you don't need to call the ctor overload that sets that.

like image 194
Matt Casto Avatar answered Jan 18 '23 02:01

Matt Casto