所以在这个特定的MVVM实现中,我需要几个命令。我真的厌倦了逐个实现ICommand类,所以我想出了一个解决方案,但我不知道它有多好,所以任何WPF专家的输入将不胜感激。如果你能提供更好的解决方案,甚至更好!WPF ICommand MVVM实现
我所做的是一个ICommand类和两个委托,它们将一个对象作为参数,一个委托是void(用于OnExecute),另一个是用于OnCanExecute的bool。所以在我的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");
}
}
的ICommand:
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
}
查看Karl Shifflet的RelayCommand实现:http://www.codeproject.com/KB/WPF/ExploringWPFMVVM.aspx – 2009-09-24 00:26:03