[MVVMbasics] Passing custom parameters during event-to-command redirection

All blog posts with a title that starts with [MVVMbasics] are related to the MVVMbasics framework. If you are only interested in my regular blog posts and not in MVVMbasics, ignore these. To list all articles covering MVVMbasics, go to http://mvvmbasics.mobilemotion.eu/documentation!

In version 2.0 of the MVVMbasics framework, a simple way to redirect a UI event directly to a Viewmodel Command has been introduced, via the EventToCommand keyword and the Command attached property:

<ListBox SelectionChanged="EventToCommand" mvvm:Event.Command="{Binding ListSelectionChangedCommand}" ... />

This can be used as a short cut in many situations to avoid including the Interaction framework (which usually results in long XAML code lines) or invoking Viewmodel Commands from within code-behind event handlers.

With the 2.2 release, this feature has become more flexible: An additional attached property CommandParameter has been introduced that allows passing custom parameters to the target Command instead of the generic event arguments! The CommandParameter can be specified either as fixed value, or through Data Binding:

<ListBox x:Name="List"
         mvvm:Event.Command="{Binding ListSelectionChangedCommand}"
         mvvm:Event.CommandParameter="{Binding ElementName=List, Path=SelectedItem}" />
<CustomControl DoubleClick="EventToCommand"
               mvvm:Event.Command="{Binding ActivatedCommand}"
               mvvm:Event.Command="123" />

In the Viewmodel, you instantiate the BaseCommand with a target method that accepts one parameter of type object, just as in the previous version. This parameter, however, will contain the passed parameter. Of course, it is still possible to get the raw event arguments forwarded to the Command by simple omitting the CommandParameter property, as in this case the event args will be automatically used as parameter.

Be aware, though, that you still need to declare the mvvm namespace in the View’s XAML header. In addition, please notice that Windows Phone Silverlight projects do not support the EventToCommand keyword due to a bug in the Silverlight platform. Instead you’ll need to attach the EventToCommand handler to the desired event in C# code-behind, as explained in detail in the original article presenting the MVVMbasics event-to-command binding solution!