Wpf – Why are events and commands in MVVM so unsupported by WPF / Visual Studio

commandeventsmvvmwpf

When creating an WPF application with the MVVM pattern, it seems I have to gather the necessary tools myself to even begin the most rudimentary event handling, e.g.

  • AttachedBehaviors I get from here
  • DelegateCommands I get from here

Now I'm looking for some way to handle the ItemSelected event in a ComboBox and am getting suggestions of tricks and workarounds to do this (using a XAML trigger or have other elements bound to the selected item, etc.). Ok, I can go down this road, but it seems to be reinventing the wheel. It would be nice to just have an ItemSelected command that I can handle in my ViewModel.

Am I missing some set of standard tools or is everyone doing MVVM with WPF basically building and putting together their own collection of tools just so they can do the simplest plumbing tasks with events and commands, things that take only a couple lines in code-behind with a Click="eventHandler"?

Best Answer

You're right about the complexity of commands. I try to follow the M-V-VM pattern as close as possible, but I can't justify sophisticated workarounds just to handle a simple user event.

In my opinion, it's OK to handle a user event in the View if that greatly simplifies your code. If you do handle a user event in the View, your View's code-behind should immediately call a method on the ViewModel. This way, you are still keeping your logic in the ViewModel… you just have a little plumbing code (event handler) in the View. I know the M-V-VM purists think there should be no code in the View's code-behind, but sometimes it just makes more sense to allow some simple boilerplate code like an event handler. Remember, others may have to read/modify your code in the future and it is much easier to understand an event handler than a DelegateCommand.