Back to Home

InvokeCommandAction with EventArgs as Command Parameter

January 18, 20141 minute read
InvokeCommandAction with EventArgs as Command Parameter

Expression Blend team provides the ability to wire up some events to viewmodel through commands like SelectionChanged of a ListBox, etc using System.Windows.Interactivity.dll. You can bind a Command to any event with WPF controls. There is also a way to bind command parameter also, so that view state can passed to the viewmodel.

<ListBox x:Name="list">
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}"
CommandParameter="{Binding ElementName=list, Path=SelectedItem}"/>
<str:String>Test Item 1</str:String>
<str:String>Test Item 2</str:String>
<str:String>Test Item 3</str:String>

Custom Command Action

But there are some scenarios where you need to pass the exact event args of the event to the ViewModel. For example, the Drop event, where user can drop a file from system’s windows explorer to the application. The InvokeCommandAction provided by default does not have this option. If you leave the CommandParameter property as empty, then you will get a null value in viewmodel. You could see they ignore the event args completely, by reflecting the code.

But still there is a way to achieve this. We can create our custom CommandAction inheriting from TriggerAction. I have provided the source code. This will pass the event args as the parameter if CommandParameter not specified and still works if it is specified like legacy one.

Download Source here

Happy Commanding. 🙂