Vì vậy, trong triển khai MVVM cụ thể này, tôi cần một vài lệnh. Tôi thực sự đã mệt mỏi với việc triển khai các lớp ICommand từng cái một, vì vậy tôi đã đưa ra một giải pháp, nhưng tôi không biết nó tốt như thế nào, vì vậy đầu vào của bất kỳ chuyên gia WPF nào ở đây sẽ được đánh giá cao. Và nếu bạn có thể cung cấp một giải pháp tốt hơn, thậm chí tốt hơn!WPF ICommand MVVM implementation
Điều tôi đã làm là một lớp ICommand duy nhất và hai đại biểu nhận một đối tượng làm tham số, một đại biểu bị vô hiệu (đối với OnExecute), một bool khác (cho OnCanExecute). Vì vậy, trong constructor của ICommand của tôi (được gọi bởi lớp ViewModel), tôi gửi hai phương thức, và trên mỗi phương thức ICommand tôi gọi các phương thức của các đại biểu.
Nó hoạt động thực sự tốt, nhưng tôi không chắc chắn nếu đây là một cách xấu để làm điều đó, hoặc nếu có một cách tốt hơn. Dưới đây là mã hoàn chỉnh, mọi đầu vào sẽ được đánh giá cao, thậm chí là tiêu cực, nhưng hãy xây dựng.
Cảm ơn !!
ViewModel:
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
}
Kiểm tra việc triển khai của Karl Shifflet của RelayCommand: http://www.codeproject.com/KB/WPF/ExploringWPFMVVM.aspx –