Avalonia DataGrid Enter handling

Viewed 282

I'm using Avalonia.Controls.DataGrid. By default, when the grid has focus and Enter is pressed, it automatically handles the event and moves the selection to the next item. How can I prevent this default behavior? I'd like to have a custom Enter KeyDown handler instead.

2 Answers

So the KeyDown event cannot be used here, because specifically for Enter it's swallowed by the DataGrid before custom code can handle it.

Instead, Key bindings work. You can bind the key to a command like this:

<DataGrid ...>
  <DataGrid.KeyBindings>
    <KeyBinding Gesture="Enter" Command="{Binding SelectCommand}" />
  </DataGrid.KeyBindings>
  ...
</DataGrid>

This also stops the grid from moving to next item when Enter is pressed.

Try this :

1- Give your datagrid a name (use x:name)

2- put this in your constructor :

yourDataGridName.KeyDown += yourDataGridName_KeyDown;

3- add this handler :

protected void yourDataGridName_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
         //Put your custom code here 
    }
}
Related