C# MVVM指示灯中的EventToCommand问题
我有下面的可视化树,我正试图通过EventToCommand为其发送命令。 视觉效果如下:C# MVVM指示灯中的EventToCommand问题,c#,wpf,mvvm-light,relaycommand,C#,Wpf,Mvvm Light,Relaycommand,我有下面的可视化树,我正试图通过EventToCommand为其发送命令。 视觉效果如下: <Border Background="Gray" Grid.Row="0" Margin="2" VerticalAlignment="Bottom"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseDown">
<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>
ShowVideosCmd = new RelayCommand<DependencyObject>(
(dpObj) =>
{
messenger.Default.Send<string>("ShowVideos");
},
(dpObj) => true
);
单击命令所附加到的边框时,会出现以下弹出错误:
发生“System.InvalidCastException”类型的未处理异常
在GalaSoft.MvvmLight.WPF4.dll中
其他信息:无法强制转换类型为的对象
“System.Windows.Input.MouseButtonEventArgs”以键入
“System.Windows.DependencyObject.”
然后在viemModel中创建我的命令,如下所示:
<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>
ShowVideosCmd = new RelayCommand<DependencyObject>(
(dpObj) =>
{
messenger.Default.Send<string>("ShowVideos");
},
(dpObj) => true
);
ShowVideosCmd=新的中继命令(
(dpObj)=>
{
messenger.Default.Send(“ShowVideos”);
},
(dpObj)=>正确
);
我做错了什么?错误消息是不言自明的:在您的
RelayCommand
中,您希望命令参数为DependencyObject
,但您得到了一个MouseButtonEventArgs
,这是正常的,因为您订阅了MouseDown
事件
EventToCommand
当事件激发时,它使用以下参数之一执行命令:
- 如果
的值为NOTCommandParameter
则将其用作参数,因此该命令应如下所示:null
RelayCommand
- 如果
和的PassEventArgsToCommand='true'
是CommandParameter
它使用eventargs作为命令 参数因此,您需要将命令定义为null
李>中继命令
- 如果
且PassEventArgsToCommand='false'
为CommandParameter
,则不会执行该命令null
RelayCommand
并检查参数类型。这就是为什么我认为同时使用PassEventArgsToCommand
和CommandParameter
是不好的做法
回到异常:
在您的情况下,它将CommandParameter=“{Binding Videos}”
返回null,这就是为什么您将MouseButtonEventArgs
作为命令参数
想知道为什么
{Binding Videos}
为空,您可以在运行时检查VS中的输出窗口以查找绑定错误。错误消息是不言自明的:在您的RelayCommand
中,您希望命令参数作为DependencyObject
,但您有一个MouseButtonEventArgs
,这是正常的,因为您已订阅到MouseDown
事件
EventToCommand
当事件激发时,它使用以下参数之一执行命令:
- 如果
的值为NOTCommandParameter
则将其用作参数,因此该命令应如下所示:null
RelayCommand
- 如果
和的PassEventArgsToCommand='true'
是CommandParameter
它使用eventargs作为命令 参数因此,您需要将命令定义为null
李>中继命令
- 如果
且PassEventArgsToCommand='false'
为CommandParameter
,则不会执行该命令null
RelayCommand
并检查参数类型。这就是为什么我认为同时使用PassEventArgsToCommand
和CommandParameter
是不好的做法
回到异常:
在您的情况下,它将CommandParameter=“{Binding Videos}”
返回null,这就是为什么您将MouseButtonEventArgs
作为命令参数
要找出{Binding Videos}
为空的原因,可以在运行时检查VS中的输出窗口以查找绑定错误