Search code examples
c#wpfsilverlightdesign-patternsmvp

Are WPF and Silverlight command implementations useless for the M-V-VM (M-V-P) pattern?


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:

How should I handle multiple events per control w/command pattern using MVVM in Silverlight?


Solution

  • 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.