[英]MVVM Light : RelayCommand : define it lazy or in constructor?
There are several examples on how to define a RelayCommand in the ViewModel :有几个关于如何在ViewModel 中定义RelayCommand 的示例:
Option 1 ( lazy ):选项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;
}
}
Option 2 (in constructor)选项 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;}
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.
大多数人不喜欢在属性 getter 中有一堆逻辑,如果他们可以避免的话。
Personally, I prefer having a real method to call instead of an anonymous method.就个人而言,我更喜欢有一个真正的方法来调用而不是匿名方法。 My ViewModels look something like this.
我的 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...
}
}
Notice that if you're not using the enable command, you don't need to call the ctor overload that sets that.请注意,如果您不使用 enable 命令,则无需调用设置该命令的 ctor 重载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.