7

I have a problem with datagrid control in wpf . when I press enter I want to load selected items in a set of controls, but it seems that datagrid.KeyDown is already handled and it goes to the next item.

I tried using keyup but this event fires when the datagrid keydown had been fired and datagrid goes to the next item.

any idea to handle keydown completely ?

Pouyan
  • 2,849
  • 8
  • 33
  • 39

3 Answers3

9

Use the PreviewKeyDown event instead of KeyDown

Rachel
  • 130,264
  • 66
  • 304
  • 490
  • 2
    you know... of course using PreviewKeyDown resolve the problem but it's like wiping the whole question.... what if I insist to use keydown event for datagrid ? isn't there a way to handle that ? – Pouyan Jul 26 '11 at 11:33
  • @Pouyan I don't think there is because some controls set `e.Handled = true` on certain events, which means the events will not continue through the event tree – Rachel Jul 27 '11 at 18:21
  • 2
    I'm sure there is a way. Because if some controls originally handle their events thyself the developer couldn't have seen that event in the designer. The fact that I see KeyDown event in datagrid means that i absolutely CAN handle it my own. it's like giving you access to a bank account but tell you just can see it and transactions are handled by someone else. – Pouyan Jul 28 '11 at 05:45
  • In my case the grid is swallowing preview events also, specifically PreviewMouseLeftButtonUp – MikeKulls May 21 '12 at 05:34
0

Maybe KeyDown is handled by a ClassHandler.
Instance listeners come after class listeners.

A good explanation on MSDN.

jan
  • 1,581
  • 2
  • 19
  • 34
0

You can add a comma-separated list of handlers to an event...

Private Sub dgMyDataGrid_KeyDown(sender As Object, e As KeyEventArgs) Handles dgMyDataGrid.KeyDown, dgSymbols.PreviewKeyDown
    
    ' Perform event programming here...    
    
End Sub

This triggers handling of the "preview" event at the same time as the keydown event, so you don't have to write more than one module.

user20568
  • 51
  • 4
  • just to clarify: this doesn't trigger events "at the same time". it executes the sub twice (if the events are actually fired and not marked as "handled" by someone), once for each event, which, i think, may often not be what you really want. – mike Dec 07 '21 at 21:55
  • Indeed, @mike, you're right. However, it sometimes does surface events I can then respond to. Example: I've seen some code completely bypass simple tests to display a MsgBox if the user clicks a button, where code goes completely ignored and nothing appears on the screen. – user20568 Jan 19 '22 at 02:40