views:

758

answers:

3

Please excuse my ignorance, I only started coding in Silverlight recently.

I tried implementing the command pattern in Silverlight and hit a wall. They say commands are great, because you can write them into xaml, so you can keep your code-behind clean, also you have loose coupling between your view and your viewmodel because there is no direct reference to the viewmodel in the view.

You can not keep your code-behind clean, because you can bind only one command to a control, and you have to decide which event will fire your command when you bind it. If a control has 30 events, you have to choose one for commanding. The other 29 will execute the other commands from event handlers from the code behind.

Loose coupling can be achieved more simply by dependency injection, commands add a useless layer of indirection that gives nothing extra, they only make it a bit harder to maintain your code. It is easier to maintain your code, when you are programming against an interface and see exactly what method gets called, then when you have to keep jumping between your command definitions and your viewmodel.

Did I miss anything, or commands are really not meant to be used for view and viewmodel interaction?

Please see the following question. This is why I don't get all the hype with commands:

http://stackoverflow.com/questions/567672/how-should-i-handle-multiple-events-per-control-w-command-pattern-using-mvvm-in-s

A: 

I believe that you could trick your event handlers with attached behavior pattern. Please see following url for more information:

http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

Oleg
There are multiple implementations which use attached behaviors for implementing commands, but none of them solves the problem of handling multiple events on the same control.
Sandor Davidhazi
+1  A: 

SL 2.0 is not so powerful as WPF, you will have to write some code behind :-(.

Not sure if you have read this article about MVVM and SL, talks about commands limitations on SL:

http://msdn.microsoft.com/en-us/magazine/dd458800.aspx

Braulio
Actually, WPF has the same limitation as Silverlight concerning commands. You can assign a command only to one event per control type.
Sandor Davidhazi
+2  A: 

Take a look at Prism (http://prism.codeplex.com) and their DelegateCommand<> infrastructure. Its a good solution for Silverlight and WPF to create commands in the ViewModel (or Presenter) and bind directly to it. Also in Silverlight 3, Behaviors can give you some of this same XAML-based syntax.

Shawn Wildermuth
Thank you, this solution seems like a valid one! I didn't implement it yet in the solution, but the samples look promising.
Sandor Davidhazi