Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 响应事件时运行命令_Wpf_Xaml_Events_Mvvm_Command - Fatal编程技术网

Wpf 响应事件时运行命令

Wpf 响应事件时运行命令,wpf,xaml,events,mvvm,command,Wpf,Xaml,Events,Mvvm,Command,基本上,我尝试响应WPF控件引发的事件,但不是使用代码隐藏,而是运行命令(ICommand) 我有一个名为CouponView的窗口和一个名为SingleBetView的用户控件。我有一个名为CouponViewModel的ViewModel,它是CouponView的DataContext,还有一个名为BetsViewModel的ViewModel,它是SingleBetView的DataContext。我正在将SingleBetView添加到CouponView,并将其数据上下文设置为: &

基本上,我尝试响应WPF控件引发的事件,但不是使用代码隐藏,而是运行命令(ICommand)

我有一个名为CouponView的窗口和一个名为SingleBetView的用户控件。我有一个名为CouponViewModel的ViewModel,它是CouponView的DataContext,还有一个名为BetsViewModel的ViewModel,它是SingleBetView的DataContext。我正在将SingleBetView添加到CouponView,并将其数据上下文设置为:

<View:SingleBetView DataContext="{Binding Path=BetsViewModel}" />
public DownArrowRepeatsStakesCommand DownArrowRepeatsStakesCommand { get; set; }
然后,我在BetsViewModel的构造函数中实例化它,如下所示:

DownArrowRepeatsStakesCommand = new DownArrowRepeatsStakesCommand(_bets); //_bets is an observable collection, my DataGridView is bound to this ObservableCollection and when the KeyDown is pressed, I want to update various elements
Command="{Binding DownArrowRepeatsStakesCommand}"
我知道我可以很容易地将按钮链接到命令,只需将其绑定到ViewModel中的实例,如下所示:

DownArrowRepeatsStakesCommand = new DownArrowRepeatsStakesCommand(_bets); //_bets is an observable collection, my DataGridView is bound to this ObservableCollection and when the KeyDown is pressed, I want to update various elements
Command="{Binding DownArrowRepeatsStakesCommand}"
但这似乎不适用于应对事件:

KeyDown="{Binding DownArrowRepeatsStakesCommand}
我得到以下运行时错误:

A 'Binding' cannot be set on the 'AddKeyDownHandler' property of type 'DataGrid'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
我尝试了Reed关于使用MVVM light的建议(我通过NuGet添加了MVVM light)并找到了一些步骤,这些步骤在理论上很好,但我得到了以下错误:

无法加载文件或程序集“GalaSoft.MvvmLight.Extras.WPF4”, PublicKeyToken=1673DB7D590600AD'或其依赖项之一。这个 系统找不到指定的文件

以下是我添加到DataGrid的XAML:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="KeyUp">
        <command:EventToCommand Command="{Binding DownArrowRepeatsStakesCommand, Mode=OneWay}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

以下是一个屏幕截图(无内部异常):

我还收到以下两条警告:

  • 无法将“EventTrigger”类型的实例添加到“TriggerCollection”类型的集合中。仅允许“T”类型的项目
  • 无法将“EventTrigger”类型的值添加到“TriggerCollection”类型的集合或字典中
有点困惑

是否有任何方法可以完成我试图在命令中执行的操作,或者它是唯一选项背后的代码


谢谢

这在WPF中不受直接支持。您需要一些额外的类似“胶水”的实现,它允许您获取任何事件,并将其映射到ViewModel中的
ICommand

谢谢,这在理论上看起来很好,但在实践中效果不太好,我已经用出错的地方更新了我的问题,也许您会看到我没有看到的东西。