[英]How to trigger a RelayCommand manually in WPF?
我有一个代码片段,如下所示:
XAML
...
<DataGrid>
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewKeyDown">
<mvvm:EventToCommand Command="{Binding KeyDownLocationDG}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>
视图模型
public class A
{
public RelayCommand<KeyEventArgs> KeyDownLocationDG { get; set; }
public A()
{
KeyDownLocationDG = new RelayCommand<KeyEventArgs>(TestMethod);
App.processBarcodeData = new App.ProcessBarCodeData((barcode) =>
{
DoSomething();
// then I ONLY want to trigger KeyDownLocationDG command here
});
}
private void TestMethod(KeyEventArgs e)
{
...
}
}
我也有一个MainWindow.xaml文件,在代码隐藏(MainWindow.xaml.cs)中有RawPresentationInput
对象的KeyPressed
事件。 每次触发此事件时,我都会调用processBarcodeData
委托。 如果按DataGrid上的一个键,则将立即执行TestMethod
,但我不想这样做,我要使它只能在DoSomething()完成后才能运行。
有人能帮我吗? 谢谢。
RelayCommand
是一个ICommand
,与所有其他ICommand
类一样,您只需将其称为Execute()
函数即可。
在Window.KeyPress
之前调用DataGrid.PreviewKeyDown
事件。
在MainWindow中使用PreviewKeyDown
事件,或在网格中指定所有操作:
<DataGrid>
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewKeyDown">
<mvvm:CallMethodAction Method="DoSomething" />
<mvvm:EventToCommand Command="{Binding KeyDownLocationDG}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>`
在第二种情况下,您还应该设置KeyEventArgs.IsHandled = true;
为了防止将事件扩展到Window,但可能会产生不良影响
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.