MVVM Light:RelayCommand:定义它是lazy还是在构造函数中? [英] MVVM Light : RelayCommand : define it lazy or in constructor?

查看:425
本文介绍了MVVM Light:RelayCommand:定义它是lazy还是在构造函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有几个范例说明如何在 ViewModel 中定义 RelayCommand

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

选项1 strong> lazy ):

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

选项2(在 strong>

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 ?

推荐答案

这取决于你喜欢什么风格。大多数人不喜欢在属性获取器中有一堆逻辑,如果他们可以避免它。

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.

就个人而言,我喜欢有一个真正的方法来调用而不是匿名方法。我的ViewModel看起来像这样。

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 get; }

    public MyViewModel()
    {
        CreateCommands();
    }

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

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

请注意,如果不使用enable命令,则不需要调用ctor overload, 。

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

这篇关于MVVM Light:RelayCommand:定义它是lazy还是在构造函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆