Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ICommand better than code behind calling the VM?

Tags:

c#

.net

mvvm

wpf

I have a co-worker that asked me why he has to use the ICommand pattern.

He wants to add a button and then make an event for it in the code behind. Then from the event he wants to call a method on the ViewModel.

I gave him the obvious answer: This adds coupling between the View and the ViewModel. But he argued that the View and the ViewModel are already coupled. (We set our view's DataContext to the ViewModel in the View's code behind: DataContext = new MyViewModel();

Yes, I told him that his way adds "more coupling", but it sounded a bit lame even to me.

So, I know that ICommand is the clean way, and I do it that way. But what else does ICommand buy you besides not using an already existing coupling?

like image 385
Vaccano Avatar asked Dec 22 '11 21:12

Vaccano


People also ask

How do you call ICommand from code?

You can call the ICommand. Execute() method.

What is a command MVVM?

What's a Command? Commands are an implementation of the ICommand interface that is part of the . NET Framework. This interface is used a lot in MVVM applications, but it is useful not only in XAML-based apps.


1 Answers

  • It's not about decoupling, but how deep you can penetrate inside your ModelView hierarchy: not event pumping, but event routing, built-in in the framework.

  • It's about UI managent: Command has state (CanExecute), if assign the command to the control, if command's state becomes false, control becomes disabled. It gives you powerful UI state management way, avoiding a lot of spaghetti coding, for complicated UI especially.

like image 173
Tigran Avatar answered Nov 04 '22 10:11

Tigran