【问题标题】:MVVM Light : RelayCommand : define it lazy or in constructor?MVVM Light:RelayCommand:定义它是惰性的还是在构造函数中?
【发布时间】:2011-03-26 22:08:13
【问题描述】:

有几个例子说明了如何在ViewModel中定义一个RelayCommand

选项 1(懒惰):

/// <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(在 构造函数中)

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

最好/最清晰的设计是什么?

【问题讨论】:

    标签: c# command mvvm-light


    【解决方案1】:

    这真的取决于你喜欢什么风格。如果可以避免的话,大多数人都不喜欢在属性 getter 中有一堆逻辑。

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

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

    请注意,如果您不使用 enable 命令,则无需调用设置该命令的 ctor 重载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多