如何在 WPF 中手动触发 RelayCommand?
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>
ViewModel
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()
函数即可。
DataGrid.PreviewKeyDown
事件在 Window.KeyPress
.
之前调用
在 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,但它可能会产生不良影响
我有如下代码片段:
XAML
...
<DataGrid>
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewKeyDown">
<mvvm:EventToCommand Command="{Binding KeyDownLocationDG}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>
ViewModel
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()
函数即可。
DataGrid.PreviewKeyDown
事件在 Window.KeyPress
.
在 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,但它可能会产生不良影响