Delegatecommand,relaycommand和routedcommand之间的区别

Zaz*_*Zaz 47 c# command mvvm

我对命令模式感到困惑.关于这些命令有很多不同的解释.我认为下面的代码是委托命令,但在阅读了关于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.


FindProductCommandvs DelegateCommand/RelayCommand

通常,当一个实现ICommand被命名时,DelegateCommand或者RelayCommand意图是您不必编写实现该ICommand接口的类; 相反,您将必要的方法作为参数传递给DelegateCommand/ RelayCommandconstructor.

例如,您可以编写:而不是整个类.

ProductViewModel _avm;
var FindPoductCommand = new DelegateCommand<object>(
    (parameter) => _avm.FindProduct(),
    (parameter) => _avm.CanFindProduct()
);
Run Code Online (Sandbox Code Playgroud)

DelegateCommand/的一些实现RelayCommand:

有关:


FindProductCommand VS RoutedCommand

FindProductCommandFindProduct在触发时执行.

WPF的内置功能RoutedCommand可以做其他事情:它引发一个路由事件,可以由可视树中的其他对象处理.这意味着您可以将命令绑定附加到要执行的其他对象FindProduct,同时将其RoutedCommand自身专门附加到触发命令的一个或多个对象,例如按钮,菜单项或上下文菜单项.

一些相关的SO答案: