Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid: How to prevent auto change row on enter key pressed?

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.

like image 887
Quan Nguyen Avatar asked Sep 15 '25 07:09

Quan Nguyen


1 Answers

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.

like image 147
Hitesh Kansagara Avatar answered Sep 17 '25 01:09

Hitesh Kansagara