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

I'm really worried that pressing the enter key in the Datagrid moves the selection one element at a time, I would like it to be able to decide what it does in the regular keydown event.

So, I created a new class that inherits the DataGrid and overrides the OnKeyDown event and uses it as my datagrid.

This creates a completely new set of problems, since I apparently have to rewrite all the other keystrokes (arrow key, offset + arrow selection, pgup / pgdn, etc.). I tried to crack it, but it just seems pointless to spend time rewriting something that has already been written, and probably better than I can imagine.

So, how can I make an input key do what I want without messing with other default keywords for a datagrid?

Thank you in advance

+4
source share
5 answers

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

+3
source

You will need to bind the PreviewKeyDown handler to the Datagrid, and then manually check to see if Key.Enter key.

If yes, set e.Handled = true .

+9
source

A simpler implementation. The idea is to capture the keydown event and if the key is "Enter", decide which direction you want to go.
FocusNavigationDirection has several properties based on which focus can be changed.

 /// <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)); } } 
+2
source

If it works similarly to winforms, for a keypress that you are not processing, than the flag is processed as false, and it will transmit the keypress. Class KeyEventArgs

Handled Gets or sets a value indicating the current event processing state for the routed event as it passes along the route. (Inherited from RoutedEventArgs.)

0
source

PreviewKeyDown with Handled = true is a bad solution. This will stop working with Key during the tunneling phase and never trigger a key event. Simply put, it will eat any Enter key presses. This means that the top panels will never receive a KeyDown (imagine that your window accepts something on ENTER KeyDown ...).

The correct solution is what Anthony suggested: leave Handled = false - so that it keeps bubbling - and skip processing. Input to 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); } } 
0
source

Source: https://habr.com/ru/post/1347803/


All Articles