Home > front end >  Prevent DataGrid from handling Enter-key
Prevent DataGrid from handling Enter-key

Time:09-12

I have a readonly DataGrid showing items inside a window that is shown as dialog. This dialog also has two buttons, one to confirm and one to cancel the dialog. The confirm button's IsDefault property is set to true, the cancel button's IsCancel property is set to true. I want to keep up the default dialog button behaviour, i.e. confirming and closing the dialog when pressing the confirm button or ENTER or cancelling and closing it by pressing the cancel button or ESCAPE.

Unfortunately the DataGrid consumes the KeyDown event of the ENTER-key and selects the next row inside the grid. Because the KeyDown event is marked as handled by the DataGrid the dialog will not be confirmed and stays open. My desired behaviour is that the selected row is not changed and the dialog will be confirmed and closed.

I could create my own DataGrid-derived type an overwrite OnKeyDown as follows:

public class MyDataGrid : DataGrid
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.Key != Key.Enter)
        {
            base.OnKeyDown(e);
        }
    }
}

But I was wondering if there is another way without having to create a derived type to achieve my goal.

CodePudding user response:

You can use the curernt DataGrid.

<DataGrid PreviewKeyDown="DataGrid_PreviewKeyDown"/>
private void DataGrid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        // This makes this key pressed event end here.
        e.Handled = true;
        // Do what you need to do here...
    }
}
  • Related