Difference between Delegatecommand, relaycommand and routedcommand

后端 未结 1 1974
再見小時候
再見小時候 2020-12-04 15:29

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 r

相关标签:
1条回答
  • 2020-12-04 16:03

    Your FindProductCommand class implements the ICommand interface, which means 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.


    FindProductCommand vs DelegateCommand/RelayCommand

    Generally, when an implementation of ICommand is named DelegateCommand or RelayCommand, the intention is that you don't have to write a class that implements the ICommand interface; rather, you pass the necessary methods as parameters to the DelegateCommand / RelayCommand constructor.

    For example, instead of your entire class, you could write:

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

    (Another, perhaps greater benefit than the savings in boilerplate code -- if you instantiate the DelegateCommand / RelayCommand within your viewmodel, your command has access to the internal state of that viewmodel.)

    Some implementations of DelegateCommand / RelayCommand:

    • Microsoft Prism DelegateCommand reference
    • WPF Tutorial implementation of ICommand called DelegateCommand
    • Another implementation also called DelegateCommand
    • The original implementation of RelayCommand by Josh Smith

    Related:

    • Relay/ICommand vs DelegateCommand -- Differences

    FindProductCommand vs RoutedCommand

    Your FindProductCommand will execute FindProduct when triggered.

    WPF's built-in RoutedCommand does something else: it raises a routed event which can be handled by other objects in the visual tree. This means you can attach a command binding to those other objects to execute FindProduct, while attaching the RoutedCommand itself specifically to one or more objects that trigger the command, e.g. a button, a menu item, or a context menu item.

    Some related SO answers:

    • MVVM Routed and Relay Command
    • WPF ICommand vs RoutedCommand
    0 讨论(0)
提交回复
热议问题