问题描述
我对命令模式感到困惑。有关命令有这么多不同的解释。我认为下面的代码是delegatecommand,但在阅读了关于relaycommand后,我有疑问。
I'm confused about command pattern. There are so many different explanations about the commands. I thought the code below was delegatecommand, but after reading about the relaycommand, I am in doubt.
relaycommand,delegatecommand和routedcommand之间的区别是什么。是否可以在与我发布的代码相关的示例中显示?
What is the difference between relaycommand, delegatecommand and routedcommand. Is it possible to show in examples that have relevance to my posted code?
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
,因此可以用作WPF command 。它既不是 DelegateCommand
也不是 RelayCommand
,也不是 RoutedCommand
,这是 ICommand
接口的其他实现。
Your class is a FindProductCommand
which implements the interface ICommand
so it can be used as a WPF command. It is neither a DelegateCommand
nor a RelayCommand
, nor is it a RoutedCommand
, which are other implementations of the ICommand
interface.
通常, $ c> ICommand 命名为 DelegateCommand
或 RelayCommand
,意图是您不应必须实现 ICommand
接口,而是将必要的方法作为参数传递给 DelegateCommand
/ RelayCommand
构造函数。而不是整个类,你可以写:
Generally, when an implementation of ICommand
is named DelegateCommand
or RelayCommand
, the intention is that you should not have to implement the ICommand
interface, but rather pass the necessary methods as parameters to the DelegateCommand
/ RelayCommand
constructor. Instead of your entire class, you could write:
ProductViewModel _avm;
var FindPoductCommand = new DelegateCommand<object>(
(parameter) => _avm.FindProduct(),
(parameter) => _avm.CanFindProduct()
);
至于RoutedCommand和RelayCommand / DelegateCommand之间的区别,请参阅。
As far as the difference between RoutedCommand and RelayCommand/DelegateCommand, see here.
-
- 也称为
DelegateCommand
- 的原始实现
- Microsoft Prism DelegateCommand reference
- WPF Tutorial implementation of
ICommand
calledDelegateCommand
- Another implementation also called
DelegateCommand
- The original implementation of
RelayCommand
by Josh Smith
这篇关于Delegatecommand,relaycommand和routed命令之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!