所以在我正在做的这个特定的 MVVM 实现中,我需要几个命令。我真的厌倦了一个个实现 ICommand 类,所以我想出了一个解决方案,但我不知道它有多好,所以这里任何 WPF 专家的输入将不胜感激。如果你能提供更好的解决方案,那就更好了。
我所做的是一个 ICommand 类和两个将对象作为参数的委托,一个委托是 void(用于 OnExecute),另一个是布尔型(用于 OnCanExecute)。因此,在我的 ICommand 的构造函数(由 ViewModel 类调用)中,我发送了两个方法,并在每个 ICommand 方法上调用了委托的方法。
它真的很好用,但我不确定这是否是一种不好的方法,或者是否有更好的方法。以下是完整的代码,任何输入将不胜感激,即使是负面的,但请具有建设性。
视图模型:
public class TestViewModel : DependencyObject
{
public ICommand Command1 { get; set; }
public ICommand Command2 { get; set; }
public ICommand Command3 { get; set; }
public TestViewModel()
{
this.Command1 = new TestCommand(ExecuteCommand1, CanExecuteCommand1);
this.Command2 = new TestCommand(ExecuteCommand2, CanExecuteCommand2);
this.Command3 = new TestCommand(ExecuteCommand3, CanExecuteCommand3);
}
public bool CanExecuteCommand1(object parameter)
{
return true;
}
public void ExecuteCommand1(object parameter)
{
MessageBox.Show("Executing command 1");
}
public bool CanExecuteCommand2(object parameter)
{
return true;
}
public void ExecuteCommand2(object parameter)
{
MessageBox.Show("Executing command 2");
}
public bool CanExecuteCommand3(object parameter)
{
return true;
}
public void ExecuteCommand3(object parameter)
{
MessageBox.Show("Executing command 3");
}
}
指令:
public class TestCommand : ICommand
{
public delegate void ICommandOnExecute(object parameter);
public delegate bool ICommandOnCanExecute(object parameter);
private ICommandOnExecute _execute;
private ICommandOnCanExecute _canExecute;
public TestCommand(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod)
{
_execute = onExecuteMethod;
_canExecute = onCanExecuteMethod;
}
#region ICommand Members
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return _canExecute.Invoke(parameter);
}
public void Execute(object parameter)
{
_execute.Invoke(parameter);
}
#endregion
}