【问题标题】:Difference between Delegatecommand, relaycommand and routedcommandDelegatecommand、relaycommand 和 routedcommand 的区别
【发布时间】:2012-12-20 06:45:17
【问题描述】:

我对命令模式感到困惑。关于命令有很多不同的解释。我以为下面的代码是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; }
    }

}

【问题讨论】:

标签: c# mvvm command


【解决方案1】:

您的FindProductCommand 类实现了ICommand 接口,这意味着它可以用作WPF command。它既不是DelegateCommand也不是RelayCommand,也不是RoutedCommand,它们是ICommand接口的其他实现。


FindProductCommandDelegateCommand/RelayCommand

通常,当ICommand 的实现被命名为DelegateCommandRelayCommand 时,目的是您不必编写实现ICommand 接口的类;相反,您将必要的方法作为参数传递给 DelegateCommand / RelayCommand 构造函数。

例如,代替整个班级,你可以写:

ProductViewModel _avm;
var FindPoductCommand = new DelegateCommand<object>(
    parameter => _avm.FindProduct(),
    parameter => _avm.CanFindProduct()
);

(另一个,也许比节省样板代码更大的好处 - 如果您在视图模型中实例化 DelegateCommand / RelayCommand,您的命令可以访问该视图模型的内部状态。)

DelegateCommand/RelayCommand的一些实现:

相关:


FindProductCommandRoutedCommand

您的FindProductCommand 将在触发时执行FindProduct

WPF 的内置 RoutedCommand 做了其他事情:它引发了一个 routed event,它可以被可视化树中的其他对象处理。这意味着您可以将命令绑定附加到其他对象以执行FindProduct,同时将RoutedCommand 本身专门附加到触发命令的一个或多个对象,例如按钮、菜单项或上下文菜单项。

一些相关的 SO 答案:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-07
    • 2022-11-30
    • 1970-01-01
    • 2013-06-04
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多