简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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