title: Programmatically Tab Backwards in WPF
body: <p>I have a fairly simple WPF app- at the top is a series of text and combo boxes (all with <code>TabIndex</code> 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.</p>
  
  <p>Pressing Shift + Tab on the keyboard works fine everywhere. <em>But</em> 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).</p>
  
  <p>In one button I have...</p>
  
  <pre><code>private void ButtonRight_Click(object sender, System.Windows.RoutedEventArgs e)
  {
      (Keyboard.FocusedElement as UIElement).MoveFocus( new TraversalRequest(FocusNavigationDirection.Next));
  }
  </code></pre>
  
  <p>Which works <em>perfectly</em> for tabbing forward- so you would think using <code>FocusNavigationDirection.Previous</code> 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 <code>MoveFocus</code> on various parents and the main window itself but those don't work either.</p>
  
  <p>Another thing I tried was...</p>
  
  <pre><code>System.Windows.Forms.SendKeys.SendWait("+{TAB}");
  </code></pre>
  
  <p>To try and send the Shift + Tab event manually... which sets the focus to nothing at all! (Note that <code>SendKeys.Send</code> doesn't work in WPF; <code>SendWait</code> must be used)</p>
  
  <p>I have also tried...</p>
  
  <pre><code> 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);
  </code></pre>
  
  <p>Which sets the focus to the very first text box at the top of the application!</p>
  
  <p>I have no idea where to go from here. Ideally, <code>TraversalRequest(FocusNavigationDirection.Previous)</code> would just work but that's not the case. Maybe it has something to do with how my XAML is laid out?</p>