I have a window with several single-line Textboxes and one DataGrid (.Net 4.5 on Windows8).
I'd like to route navigation events (Up/Down/PgUp/PgDn, etc) to the grid, regardless of which control has the focus.
I tried overriding PreviewKeyDown in the main window like this:
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Up:
case Key.Down:
myDataGrid.RaiseEvent(e);
break;
}
}
The problem is that I'm getting a StackOverflowException because the events keep reflecting back to Window_PreviewKeyDown
.
I tried the following [ugly] workaround:
bool bEventRaised = false;
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if ( bEventRaised )
{
bEventRaised = false;
return;
}
switch (e.Key)
{
case Key.Up:
case Key.Down:
bEventRaised = true;
myDataGrid.RaiseEvent(e);
break;
}
}
I would have preferred to replace if ( bEventRaised )
with if ( sender == myDataGrid )
, but alas, the sender is always the main window.
Nonetheless, this got me a bit further. I am now able to see the keyboard event reaching myDataGrid.PreviewKeyDown
, but still - the event does not get fired inside myDataGrid.
I'd love to get some help understanding what I'm doing wrong, or if there's a different way to route the events to the child DataGrid.
Thanks.