그래서이 특정 MVVM 구현에서는 몇 가지 명령이 필요합니다. ICommand 클래스를 하나씩 구현하는 것에 지쳐 있었기 때문에 해결책을 생각해 냈습니다.하지만 얼마나 좋은지 모릅니다. 따라서 WPF 전문가의 의견을 크게 환영 할 것입니다. 그리고 더 나은 솔루션을 제공 할 수 있다면 더욱 좋습니다!WPF ICommand MVVM 구현
하나의 ICommand 클래스와 매개 변수로 하나의 대리자를 사용하는 두 명의 대리자는 하나의 대리자가 void (OnExecute의 경우)이고 다른 하나가 (OnCanExecute의 경우)입니다. 따라서 ViewModel 클래스에서 호출되는 ICommand의 생성자에서 두 메서드를 보내고 각 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 –