I have the following visual tree for which I am trying to send a command through the EventToCommand. The visual is as follow :
<Border Background="Gray" Grid.Row="0" Margin="2" VerticalAlignment="Bottom">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown">
<cmd:EventToCommand
Command="{Binding ShowVideosCmd}"
PassEventArgsToCommand="True"
CommandParameter="{Binding Videos}">
</cmd:EventToCommand>
</i:EventTrigger>
</i:Interaction.Triggers>
</Border>
When clicking on the border where the command is attached to I get the following popup error :
"An unhandled exception of type 'System.InvalidCastException' occurred in GalaSoft.MvvmLight.WPF4.dll
Additional information: Unable to cast object of type 'System.Windows.Input.MouseButtonEventArgs' to type 'System.Windows.DependencyObject'. "
My command is then created in a viemModel as follow :
ShowVideosCmd = new RelayCommand<DependencyObject>(
(dpObj) =>
{
messenger.Default.Send<string>("ShowVideos");
},
(dpObj) => true
);
What did I do wrong ?
The error message is quite self explanatory: in you
RelayCommand<DependencyObject>you've expected the command parameter as aDependencyObjectbut you've got anMouseButtonEventArgswhich is normal because you've subscribed to theMouseDownevent.The
EventToCommandwhen the event fires it exectues the command with one of following parameter:CommandParameteris NOTnullit uses it as the parameter so the command should look like:RelayCommand<typeOfTheSpecifiedCommandPameter>PassEventArgsToCommand='true'and the value of theCommandParameterisnullit uses the eventargs as the command parameter. So you need to define your command asRelayCommand<MouseButtonEventArgs>.PassEventArgsToCommand='false'and theCommandParameterisnullit does not execute the command at all.Note:
So you need to define differently your command for the two cases. At the need you have to use
RelayCommand<object>and check the parameter type. That's why I think it is bad practice to usePassEventArgsToCommandandCommandParameterat the same time.Back to the exception:
In your case it seams
CommandParameter="{Binding Videos}"returns null that is why you get theMouseButtonEventArgsas the command parameter.To figure out why
{Binding Videos}is null you can check the Output window in VS during runtime looking for binding errors.