MVVM Light:RelayCommand:定义它是惰性的还是在构造函数中?
有几个关于如何在 ViewModel 中定义 RelayCommand 的示例:
选项 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(在 构造函数中)
/// <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;}
最好/最清晰的设计是什么?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这实际上取决于您喜欢什么风格。大多数人不喜欢在属性获取器中包含一堆逻辑(如果可以避免的话)。
就我个人而言,我更喜欢调用真正的方法而不是匿名方法。我的 ViewModel 看起来像这样。
请注意,如果您不使用启用命令,则无需调用设置该命令的构造函数重载。
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.
Notice that if you're not using the enable command, you don't need to call the ctor overload that sets that.