Quan Nguyen
Quan Nguyen

Reputation: 582

How to trigger a RelayCommand manually in WPF?

I have a code snippet as below:

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)
    {
         ...
    }
}

I also have a MainWindow.xaml file, there is a KeyPressed event of RawPresentationInput object in the code-behind (MainWindow.xaml.cs). Everytime this event fired, I'll call processBarcodeData delegate. If I press a key on DataGrid, the TestMethod will be executed immediately, but I don't want to do that, what I want is to make it can only run after DoSomething() done.

Can someone help me? Thanks.

Upvotes: 1

Views: 2249

Answers (2)

Liero
Liero

Reputation: 27338

DataGrid.PreviewKeyDown event is called earlier that Window.KeyPress.

Either use PreviewKeyDown event in MainWindow, or specify all the actions in the grid:

<DataGrid>
   <i:Interaction.Triggers>
       <i:EventTrigger EventName="PreviewKeyDown">
           <mvvm:CallMethodAction Method="DoSomething" />
           <mvvm:EventToCommand Command="{Binding KeyDownLocationDG}" />
       </i:EventTrigger>
   </i:Interaction.Triggers> 
</DataGrid>`

In the second case you should also set KeyEventArgs.IsHandled = true; in order to prevent bubling the event down to Window, but it may have undesired effects

Upvotes: 2

Mark Feldman
Mark Feldman

Reputation: 16119

RelayCommand is an ICommand, and like all other ICommand classes you just call it's Execute() function.

Upvotes: 6

Related Questions