EventToCommand issue in MVVM Light

无人久伴 提交于 2019-12-25 02:43:38

问题


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:


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.



来源:https://stackoverflow.com/questions/9101957/eventtocommand-issue-in-mvvm-light

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!