繁体   English   中英

如何在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>

视图模型

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM