Override the enter key, but keep default behavior for other keys in a wpf datagrid

倖福魔咒の 提交于 2019-12-04 09:55:21

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);)

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.

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));
    }
}

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.)

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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!