Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 507
Steinthor.palsson Avatar asked Dec 07 '22 22:12

Steinthor.palsson


2 Answers

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.

like image 103
Robin Maben Avatar answered Dec 11 '22 08:12

Robin Maben


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

like image 21
anthonyvd Avatar answered Dec 11 '22 07:12

anthonyvd