c# - Delegatecommand、relaycommand、routedcommand的区别

标签 c# mvvm command

我对命令模式感到困惑。关于命令有很多不同的解释。我认为下面的代码是 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 的其他实现界面。


FindProductCommandDelegateCommand/RelayCommand

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

例如,您可以这样写:

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

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

DelegateCommand/RelayCommand 的一些实现:

相关:


FindProductCommandRoutedCommand

您的 FindProductCommand 将在触发时执行 FindProduct

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

一些相关的 SO 答案:

关于c# - Delegatecommand、relaycommand、routedcommand的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14180688/

相关文章:

c# - 通过文件共享、用户身份验证通过网络复制文件

wpf - 在 WPF 中设置数据网格的可见性

silverlight - MVVM Light EventToCommand 在 WP7 Pivot DataTemplate 中不起作用

c# - Windows Phone 中动画编译错误

c# - 如何检查互联网连接?

c# - 获取指定范围内数组中元素计数的方法

c#-4.0 - 有没有办法在不使用插件的情况下以Xamarin形式(软件模式-mvvm)创建弹出窗口?

c# - ViewModel 中用于 INotifyPropertyChanged 模型中原始属性的 getter 和 setter

linux - 如何粘贴到终端?

linux - 只打印命令结果的一部分