基本上,我试图响应 WPF 控件引发的事件,但不是使用代码隐藏,而是运行命令(ICommand)。
我有一个名为 CouponView 的窗口和一个名为 SingleBetView 的 UserControl。我有一个名为 CouponViewModel 的 ViewModel,它是 CouponView 的 DataContext,还有一个名为 BetsViewModel 的 ViewModel,它是 SingleBetView 的 DataContext。我将 SingleBetView 添加到 CouponView 并将其设置为 DataContext ,如下所示:
<View:SingleBetView DataContext="{Binding Path=BetsViewModel}" />
SingleBetView 包含一个DataGrid,我要响应这个网格的KeyDown 事件。我创建了一个名为 DownArrowRepeatsStakesCommand 的 Command 类,并在 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
我知道我可以很容易地将按钮链接到我的命令,只需将其绑定到 ViewModel 中的实例,如下所示:
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 添加的)以及在此处找到的步骤,理论上很好,但出现以下错误:
无法加载文件或程序集“GalaSoft.MvvmLight.Extras.WPF4,PublicKeyToken=1673db7d5906b0ad”或其依赖项之一。该系统找不到指定的文件。
这是我添加到 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”类型的集合或字典中。
有点懵!
有什么方法可以做我在命令中尝试做的事情,或者它是唯一选项的代码隐藏?
谢谢