4
votes

It really bothers me that the pressing the enter key in a Datagrid moves the selection down one item, I'd like to be able to decide what it does in a normal keydown event.

So what I did was create a new class that inherits DataGrid and override the OnKeyDown event and use that as my datagrid.

This creates a whole new set of problems, since I apparently have to rewrite all the other keypresses (arrow key navigation, shift+arrow key selection, pgup/pgdn, etc..). I've been trying to hack it, but it just seems so pointless spending time rewriting something that has already been written and probably better then whatever I'll come up with.

So how can I make the enter key do what I want without messing with the other default keybindings of the datagrid?

Thanks in advance

5
can u please share u r code. I have the same issueKishore Kumar

5 Answers

3
votes

Just check if the key pressed is enter, if it's not, call the base event handler for KeyDown (something like base.OnKeyDown(sender, args);)

9
votes

You will need to bind a PreviewKeyDown handler to the Datagrid and then manually check whether the key value is Key.Enter.

If yes, set e.Handled = true.

2
votes

A much simpler implementation. The idea is to capture the keydown event and if the key is "Enter", decide in what direction you wish to traverse.
FocusNavigationDirection has several properties based on which the focus can be modified.

/// <summary>
/// On Enter Key, it tabs to into next cell.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LiquidityInstrumentViewsGrid_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
    var uiElement = e.OriginalSource as UIElement;
    if (e.Key == Key.Enter && uiElement != null)
    {
        e.Handled = true;
        uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}
0
votes

If it works similiarly to winforms, for the key presses that you aren't handling, than flag the handled as false, and it will pass the key press along. KeyEventArgs Class

Handled Gets or sets a value that indicates the present state of the event handling for a routed event as it travels the route. (Inherited from RoutedEventArgs.)

0
votes

PreviewKeyDown with Handled = true is a bad solution. It would stop handling Key on the tunelling phase and never bubble the key event up. Simply speaking it would eat any Enter key presses. That meant that upper panels, would never get KeyDown event (imagine that your Window accepts something on ENTER KeyDown...).

The right solution is what Anthony has suggested: to leave the Handled = false, -- so it continues bubbling -- and skip handling Enter inside DataGrid

public class DataGridWithUnhandledReturn : DataGrid
{
    /// <inheritdoc/>
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.Key == Key.Return && e.KeyboardDevice.Modifiers == ModifierKeys.None)
        {
            return;
        }

        base.OnKeyDown(e);
    }
}