3

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.

3 Answers3

3

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.

0

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 
    }
}
  • Thanks, this doesn't work, though - the Avalonia.DataGrid component is "clever" in that is handles the Enter automatically and stops it from propagating before user code can catch it. – Radovan Jankovic Jun 13 '21 at 16:01
0

https://github.com/AvaloniaUI/Avalonia/issues/10130

I use AddHandler for DataGrid. As the developer advised.

dataGrid.AddHandler(KeyDownEvent, dataGrid_PreviewKeyDown, RoutingStrategies.Tunnel);

private void dataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{  
    if (e.Key == Key.Enter)
    {
        //
        e.Handled = true;
    }
}

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 05 '23 at 11:24