I have a fairly simple WPF app- at the top is a series of text and combo boxes (all with TabIndex
set) and underneath all of them is a data grid. Users can tab through all the boxes at the top, then the application goes down into the datagrid where tabbing moves through cells in a row.
Pressing Shift + Tab on the keyboard works fine everywhere. But I'm trying to add buttons that allow the user to tab back and forth without using the keyboard (this will be a touch screen application).
In one button I have...
private void ButtonRight_Click(object sender, System.Windows.RoutedEventArgs e)
{
(Keyboard.FocusedElement as UIElement).MoveFocus( new TraversalRequest(FocusNavigationDirection.Next));
}
Which works perfectly for tabbing forward- so you would think using FocusNavigationDirection.Previous
would work the opposite way? But instead it sets focus to the very last cell in the data grid, no matter what's in focus when the button is pressed! I've tried calling MoveFocus
on various parents and the main window itself but those don't work either.
Another thing I tried was...
System.Windows.Forms.SendKeys.SendWait("+{TAB}");
To try and send the Shift + Tab event manually... which sets the focus to nothing at all! (Note that SendKeys.Send
doesn't work in WPF; SendWait
must be used)
I have also tried...
var shift = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.LeftShift) { RoutedEvent = Keyboard.KeyDownEvent };
var tab = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Tab) { RoutedEvent = Keyboard.KeyDownEvent };
InputManager.Current.ProcessInput(shift);
InputManager.Current.ProcessInput(tab);
Which sets the focus to the very first text box at the top of the application!
I have no idea where to go from here. Ideally, TraversalRequest(FocusNavigationDirection.Previous)
would just work but that's not the case. Maybe it has something to do with how my XAML is laid out?
Turns out I didn't have Focusable
set to False
on the button tabbing backwards (but it was set on the button going forwards). My mistake.