如何在 WPF 中手动触发 RelayCommand?

Qua*_*yen 1 c# wpf xaml relaycommand

我有一个代码片段如下:

XAML

...
<DataGrid>
   <i:Interaction.Triggers>
       <i:EventTrigger EventName="PreviewKeyDown">
           <mvvm:EventToCommand Command="{Binding KeyDownLocationDG}" />
       </i:EventTrigger>
   </i:Interaction.Triggers> 
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

视图模型

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)
    {
         ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我也有一个 MainWindow.xaml 文件,有一个KeyPressed事件RawPresentationInput代码隐藏(MainWindow.xaml.cs)中对象。每次触发此事件时,我都会调用processBarcodeData委托。如果我在 DataGrid 上按下一个键,TestMethod它将立即执行,但我不想这样做,我想要的是让它只能在 DoSomething() 完成后运行。

有人能帮我吗?谢谢。

Mar*_*man 5

RelayCommand是一个ICommand,并且像所有其他ICommand类一样,您只需将其称为Execute()函数。