Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: MVVM: Command vs CallMethodAction?

I'm learning the MVVM pattern with a new(small) project, and I've one question about the way to invoke actions on our controller:

I saw many tutorial where they were telling us to use Command, implying to declare a RelayCommand, initialize it and create the action called by the RelayCommand.

In the other side, I've a colleague which said me that I can use the CallMethodAction with a trigger:

<i:Interaction.Triggers> 
  <i:EventTrigger> 
    <ei:CallMethodAction MethodName="Init" TargetObject="{Binding}" /> 
  </i:EventTrigger> 
</i:Interaction.Triggers> 

For me, his approach has the advantage that I don't have to make some inits methods for commands(which may be never used).

So what am I missing? Why everybody use commands?

like image 790
J4N Avatar asked Nov 27 '12 09:11

J4N


2 Answers

Commands are out-of-the-box solution and can be attached only to elements which implement the ICommand interface. On the other hand, event triggers can be attached to any event, what makes them more flexible. I follow the general strategy to use Commands where user interactions are involved (buttons, menus) and CanExecute pattern is needed. My commands are strictly connected to visual interface (provide caption, image source, etc.). I use CallMethodAction in any other situation when I want to get rid of code-behind.

like image 142
amnezjak Avatar answered Sep 28 '22 06:09

amnezjak


Commands provide functionality for disabling in ViewModel code. That can be used to automatically disable e.g buttons bound to command. That's what makes Commands better. Besides, based on your logic you could just dynamically pluck another Command in the same slot and it will reroute the traffic from View, whereas in CallMethodAction you would have to write the rerouting logic in the called method, which would be ugly.

As you can see, it depends on what you try to accomplish and how complicated is your logic :)

like image 45
Paweł Motyl Avatar answered Sep 28 '22 08:09

Paweł Motyl