ICommand MVVM實(shí)現(xiàn)所以在我正在做的這個特定的MVVM實(shí)現(xiàn)中,我需要幾個命令。我真的厭倦了逐個實(shí)現(xiàn)ICommand類,所以我想出了一個解決方案,但我不知道它有多好,所以任何WPF專家的輸入都將非常感激。如果你能提供更好的解決方案,那就更好了。我所做的是一個ICommand類和兩個代理,它們將一個對象作為參數(shù),一個委托是void(對于OnExecute),另一個是bool(對于OnCanExecute)。因此,在我的ICommand的構(gòu)造函數(shù)(由ViewModel類調(diào)用)中,我發(fā)送了兩個方法,并在每個ICommand方法上調(diào)用委托的方法。它的效果非常好,但我不確定這是不是一個糟糕的方法,或者是否有更好的方法。下面是完整的代碼,任何輸入都會非常感激,甚至是負(fù)面的,但請建設(shè)性的。視圖模型: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; }
}
- 3 回答
- 0 關(guān)注
- 894 瀏覽
添加回答
舉報(bào)
0/150
提交
取消