我对命令模式感到困惑。关于这些命令有很多不同的解释。我认为下面的代码是委托命令,但在阅读完below命令后,我产生了疑问。
between命令、委派命令和routedcommand之间的区别是什么?可以在与我发布的代码相关的示例中显示吗?
class FindProductCommand : ICommand
{
ProductViewModel _avm;
public FindProductCommand(ProductViewModel avm)
{
_avm = avm;
}
public bool CanExecute(object parameter)
{
return _avm.CanFindProduct();
}
public void Execute(object parameter)
{
_avm.FindProduct();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}发布于 2013-01-06 18:27:22
您的FindProductCommand类实现了ICommand接口,这意味着它可以用作WPF 。它既不是DelegateCommand也不是RelayCommand,也不是RoutedCommand,这是ICommand接口的其他实现。
FindProductCommand DelegateCommand**/**RelayCommand vs
通常,当ICommand的实现被命名为DelegateCommand或RelayCommand时,其目的是不必编写实现ICommand接口的类;而是将必要的方法作为参数传递给DelegateCommand / RelayCommand构造函数。
例如,您可以编写以下代码来代替整个类:
ProductViewModel _avm;
var FindPoductCommand = new DelegateCommand<object>(
parameter => _avm.FindProduct(),
parameter => _avm.CanFindProduct()
);(另一个可能比节省样板代码更大的好处是--如果在视图模型中实例化DelegateCommand / RelayCommand,则命令可以访问该视图模型的内部状态。)
DelegateCommand / RelayCommand的一些实现
ICommand called DelegateCommandDelegateCommandRelayCommand,作者: Josh Smith相关信息:
FindProductCommand RoutedCommand vs
当触发时,您的FindProductCommand将执行FindProduct。
WPF的内置RoutedCommand做了另外一件事:它引发一个routed event,它可以由可视化树中的其他对象处理。这意味着您可以将命令绑定附加到其他对象以执行FindProduct,同时将RoutedCommand本身专门附加到触发命令的一个或多个对象,例如按钮、菜单项或上下文菜单项。
一些相关的SO答案:
https://stackoverflow.com/questions/14180688
复制相似问题