MVVM Routed and Relay Command

后端 未结 4 1525
萌比男神i
萌比男神i 2020-11-30 19:39

What is the Difference between the RoutedCommand and RelayCommand ? When to use RoutedCommand and when to use RelayCommand in MVVM pattern ?

4条回答
  •  悲哀的现实
    2020-11-30 20:02

    Regarding the use of RelayCommand and RoutedCommand in MVVM the main difference for me is the following:

    Location of code

    RelayCommand allows you to implement the command in any class (as ICommand-property with delegates), which then is conventionally databound to the control, which invokes the command. This class is the ViewModel. If you use a routed command, you will have to implement the methods related to the command in the codebehind of the control, because the methods are specified by the attributes of the CommandBinding-element. Assumed that strict MVVM means having an "empty" codebehind-file, there actually is no possibility of using standard routed commands with MVVM.

    What RS Conley said, that RelayCommand allows you to define the RelayCommand outside the ViewModel is right, but first of all it allows you to define it inside the ViewModel, which RoutedCommand doesn't.

    Routing

    On the other hand, RelayCommands do not support routing through the tree (as said before), which is not a problem, as long as your interface is based on a single viewModel. If it is not, for example if you have a collection of items with their own viewModels and want to invoke a command of the child ViewModel for each item out of the parent element at once, you will have to use routing (see also CompositeCommands).

    All in all, I would say, that standard RoutedCommands are not usable in strict MVVM. RelayCommands are perfect for MVVM but do not support routing, which you might need.

提交回复
热议问题