代码之家  ›  专栏  ›  技术社区  ›  Stef Heyenrath Dariusz Woźniak

MVVM Light:RelayCommand:在构造函数中定义它是惰性的还是惰性的?

  •  4
  • Stef Heyenrath Dariusz Woźniak  · 技术社区  · 14 年前

    有几个例子说明了如何定义 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;}
    

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

    1 回复  |  直到 13 年前
        1
  •  10
  •   Dominik Palo    4 年前

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

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

    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重载。