3

I'm using MVVM pattern in my WPF project, now I'm facing a problem as title mentioned. I found some suggestions is to use KeyEventArgs.Handled = true; like this:

private void PreviewKeyDown(object sender, KeyEventArgs e)
{
    if ((e.Key.Equals(Key.Enter)) || (e.Key.Equals(Key.Return)))
    {
        e.Handled = true;
    }
}

But I want to write it in ViewModel not code-behind of View. This example shows the way to handle Key Event with the MVVM pattern but I don't know how to pass KeyEventArgs parameter for use.

Can anyone can help me? Is this the best way to do that?

Any recommendation or suggestion would be appreciated.

Thanks in advance.

Quan Nguyen
  • 562
  • 1
  • 5
  • 20
  • 1
    All code about events interacting with controls should stay in the View. The ViewModel should be the same no matter how you display the data. if it's with a Datagrid, ListView or TextBox is not a concern for the ViewModel. – Origence Sep 21 '15 at 10:31
  • Origence is right. In your view model you can code what shall happen if a value changes. But whether a values changes or not should be a matter of a view. Do you want to perform edits in the `DataGrid` at all? Otherwise you could disable it as shown here: http://stackoverflow.com/a/6766500/4424024 – Martin Sep 21 '15 at 12:03
  • I understand, it works if I declare an event for a control in view(xaml) then auto-generate an event handler in the code-behind(xaml.cs) but with MVVM, code-behind is not allowed (that's a rule) and my DataGrid can be editable. – Quan Nguyen Sep 22 '15 at 02:09

1 Answers1

2

You can easily handle enter key press event, I have handled datagrid enter key press event like below code:

<DataGrid.InputBindings>
         <KeyBinding Key="Enter" Command="{Binding Path=DataContext.HandleEnterKeyCommand, 
                    RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
 </DataGrid.InputBindings>

Now, you can write your logic in viewmodel through command.

Hitesh Kansagara
  • 3,308
  • 3
  • 17
  • 32