0

我有以下可视化树,我正在尝试通过 EventToCommand 发送命令。视觉效果如下:

<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>

单击命令附加到的边框时,出现以下弹出错误:

“在 GalaSoft.MvvmLight.WPF4.dll 中发生了“System.InvalidCastException”类型的未处理异常

附加信息:无法将“System.Windows.Input.MouseButtonEventArgs”类型的对象转换为“System.Windows.DependencyObject”类型。"

然后在 viemModel 中创建我的命令,如下所示:

 ShowVideosCmd = new RelayCommand<DependencyObject>(
     (dpObj) =>
            { 
                 messenger.Default.Send<string>("ShowVideos");
            },
     (dpObj) => true
 );

我做错什么了 ?

4

1 回答 1

4

错误消息很容易解释:在您中,RelayCommand<DependencyObject>您期望命令参数为 aDependencyObject但您有一个MouseButtonEventArgs正常的参数,因为您已订阅该MouseDown事件。

EventToCommand事件触发时,它使用以下参数之一执行命令:

  • 如果 的值CommandParameter不是,则将 null其用作参数,因此命令应如下所示:RelayCommand<typeOfTheSpecifiedCommandPameter>
  • 如果PassEventArgsToCommand='true' 的值为 CommandParameterisnull它使用 eventargs 作为命令参数。所以你需要将你的命令定义为 RelayCommand<MouseButtonEventArgs>.
  • ifPassEventArgsToCommand='false' CommandParameterisnull它根本不执行命令。

笔记:

因此,您需要为这两种情况定义不同的命令。在需要时您必须使用RelayCommand<object>并检查参数类型。这就是为什么我认为同时使用PassEventArgsToCommandand是不好的做法CommandParameter

回到异常:

在您的情况下,它接缝CommandParameter="{Binding Videos}"返回 null 这就是您将其MouseButtonEventArgs作为命令参数的原因。

要弄清楚为什么{Binding Videos}为 null,您可以在运行时检查 VS 中的输出窗口以查找绑定错误。

于 2012-02-01T19:50:45.677 回答