我对命令模式感到困惑。关于命令有很多不同的解释。我认为下面的代码是 delegatecommand,但在阅读 relaycommand 后,我有疑问。
relaycommand、delegatecommand 和 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; }
}
}
最佳答案
您的 FindProductCommand
类实现了 ICommand
接口(interface),这意味着它可以用作 WPF command .它既不是 DelegateCommand
也不是 RelayCommand
,也不是 RoutedCommand
,后者是 ICommand
的其他实现界面。
FindProductCommand
与 DelegateCommand
/RelayCommand
通常,当 ICommand
的实现被命名为 DelegateCommand
或 RelayCommand
时,其目的是您不必编写类实现了 ICommand
接口(interface);相反,您将必要的方法作为参数传递给 DelegateCommand
/RelayCommand
构造函数。
例如,您可以这样写:
ProductViewModel _avm;
var FindPoductCommand = new DelegateCommand<object>(
parameter => _avm.FindProduct(),
parameter => _avm.CanFindProduct()
);
(另一个可能比节省样板代码更大的好处——如果您在 View 模型中实例化 DelegateCommand
/RelayCommand
,您的命令可以访问内部状态那个 View 模型。)
DelegateCommand
/RelayCommand
的一些实现:
- Microsoft Prism DelegateCommand reference
- WPF Tutorial implementation of
ICommand
calledDelegateCommand
- Another implementation也称为
DelegateCommand
- original implementation of
RelayCommand
通过乔什·史密斯
相关:
FindProductCommand
与 RoutedCommand
您的 FindProductCommand
将在触发时执行 FindProduct
。
WPF 的内置 RoutedCommand
做别的事情:它引发了一个 routed event可以由可视化树中的其他对象处理。这意味着您可以将命令绑定(bind)附加到那些其他对象以执行 FindProduct
,同时将 RoutedCommand
本身专门附加到触发命令的一个或多个对象,例如按钮、菜单项或上下文菜单项。
一些相关的 SO 答案:
关于c# - Delegatecommand、relaycommand、routedcommand的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14180688/