1

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.

Quan Nguyen
  • 562
  • 1
  • 5
  • 20
  • Are you looking for synchronizing two `KeyPressed` events? – Hari Prasad Sep 23 '15 at 04:08
  • 2
    Maybe you can use the `CanExecute` of the `ICommand`, check an example [here](http://www.codeproject.com/Tips/782169/Attributed-RelayCommand), and the DoSomething method can set a property like "Done" when is done, that you will use to enable/disable the command. – Dzyann Sep 23 '15 at 04:38
  • @Dzyann: Oh that's a good idea. – Quan Nguyen Sep 23 '15 at 05:15

2 Answers2

6

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

Mark Feldman
  • 15,731
  • 3
  • 31
  • 58
2

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

Liero
  • 25,216
  • 29
  • 151
  • 297