EventToCommand issue in MVVM Light

5.3k views Asked by At

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 ?

1

There are 1 answers

0
nemesv On BEST ANSWER

The error message is quite self explanatory: in you RelayCommand<DependencyObject> you've expected the command parameter as a DependencyObject but you've got an MouseButtonEventArgs which is normal because you've subscribed to the MouseDown event.

The EventToCommand when the event fires it exectues the command with one of following parameter:

  • If the the value of the CommandParameter is NOT null it uses it as the parameter so the command should look like: RelayCommand<typeOfTheSpecifiedCommandPameter>
  • If the PassEventArgsToCommand='true' and the value of the CommandParameter is null it uses the eventargs as the command parameter. So you need to define your command as RelayCommand<MouseButtonEventArgs>.
  • If PassEventArgsToCommand='false' and the CommandParameter is null it 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 use PassEventArgsToCommand and CommandParameter at the same time.

Back to the exception:

In your case it seams CommandParameter="{Binding Videos}" returns null that is why you get the MouseButtonEventArgs as 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.