我对命令模式感到困惑.关于这些命令有很多不同的解释.我认为下面的代码是委托命令,但在阅读了关于relaycommand后,我有点怀疑.
relay命令,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; }
}
}
Run Code Online (Sandbox Code Playgroud)
Zev*_*itz 53
您的FindProductCommand
类实现了ICommand
接口,这意味着它可以用作WPF 命令.它既不是a DelegateCommand
也不是a RelayCommand
,也不是接口的RoutedCommand
其他实现ICommand
.
FindProductCommand
vs DelegateCommand
/RelayCommand
通常,当一个实现ICommand
被命名时,DelegateCommand
或者RelayCommand
意图是您不必编写实现该ICommand
接口的类; 相反,您将必要的方法作为参数传递给DelegateCommand
/ RelayCommand
constructor.
例如,您可以编写:而不是整个类.
ProductViewModel _avm;
var FindPoductCommand = new DelegateCommand<object>(
(parameter) => _avm.FindProduct(),
(parameter) => _avm.CanFindProduct()
);
Run Code Online (Sandbox Code Playgroud)
DelegateCommand
/的一些实现RelayCommand
:
ICommand
调用DelegateCommand
DelegateCommand
RelayCommand
由约什-史密斯有关:
FindProductCommand
VS RoutedCommand
您FindProductCommand
将FindProduct
在触发时执行.
WPF的内置功能RoutedCommand
可以做其他事情:它引发一个路由事件,可以由可视树中的其他对象处理.这意味着您可以将命令绑定附加到要执行的其他对象FindProduct
,同时将其RoutedCommand
自身专门附加到触发命令的一个或多个对象,例如按钮,菜单项或上下文菜单项.
一些相关的SO答案: