有几个关于如何在 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;}
什么是最好/最清晰的设计?
答案 0 :(得分:10)
这取决于你喜欢什么样的风格。大多数人不喜欢在属性获取者中拥有一堆逻辑,如果他们可以避免它。
就个人而言,我更喜欢使用真正的方法来调用而不是匿名方法。我的ViewModel看起来像这样。
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重载。