C# 如何在WPF中手动触发RelayCommand?

C# 如何在WPF中手动触发RelayCommand?,c#,wpf,xaml,relaycommand,C#,Wpf,Xaml,Relaycommand,我有一个代码片段,如下所示: XAML ... <DataGrid> <i:Interaction.Triggers> <i:EventTrigger EventName="PreviewKeyDown"> <mvvm:EventToCommand Command="{Binding KeyDownLocationDG}" /> </i:EventTrigger> </

我有一个代码片段,如下所示:

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)
    {
         ...
    }
}
公共A类
{
公共中继命令KeyDownLocationDG{get;set;}
公共A()
{
KeyDownLocationDG=新继电器命令(测试方法);
App.processBarcodeData=新的App.processBarcodeData((条形码)=>
{
DoSomething();
//那么我只想在这里触发KeyDownLocationDG命令
});
}
私有void测试方法(KeyEventArgs e)
{
...
}
}
我还有一个MainWindow.xaml文件,在代码隐藏(MainWindow.xaml.cs)中有一个
按键
事件
RawPresentationInput
对象。每次触发此事件时,我都将调用
processBarcodeData
delegate。如果我按下DataGrid上的一个键,
TestMethod
将立即执行,但我不想这样做,我想让它只能在DoSomething()完成后运行


有人能帮我吗?谢谢。

RelayCommand
是一个
ICommand
,和所有其他
ICommand
类一样,您只需调用它的
Execute()
函数。

RelayCommand
是一个
ICommand
,就像所有其他
ICommand
类一样,您只需调用它的
Execute()
函数。

DataGrid.PreviewKeyDown
事件在
Window.KeyPress
之前调用

在主窗口中使用
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
以防止将事件向下推到窗口,但它可能会产生不希望的效果

DataGrid。PreviewKeyDown
事件在
窗口之前调用。按键

在主窗口中使用
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为了防止事件向下传播到窗口,但可能会产生不期望的效果

标题必须具有误导性,请阅读问题,这与命令执行无关。标题必须具有误导性,请阅读问题,这与命令执行无关。您是否正在寻找同步两个
按键
事件?也许您可以使用
ICommand
CanExecute
,检查一个示例,并且DoSomething方法可以在完成时设置类似“Done”的属性,您将使用它来启用/禁用该命令。@Dzyann:哦,这是个好主意。您正在寻找同步两个
按键事件吗?也许您可以使用
ICommand
CanExecute
,检查一个示例,并且DoSomething方法可以在完成时设置类似“Done”的属性,您将使用它来启用/禁用命令。@Dzyann:哦,这是个好主意。