Search code examples
c#wpffocus

How to move focus in WPF?


I wonder if there is anyway to change focus from the current control and move it to other control in WPF on TabIndex assigned controls.

Example I have controls with TabIndex 1 to 5, is there a way to jumb the focus from 1 to 5 ?

<TextBox TabIndex="1" Focusable = "true" LostFocus="test_LostFocus"/>
<TextBox TabIndex="2" Focusable = "true"/>
...
<TextBox TabIndex="5" Focusable = "true" name="LastControl"/>

.

private void test_LostFocus(object sender, RoutedEventArgs e)
{
  LastControl.Focus();
}

I tried Keyboard.Focus() and FocusManager.SetFocusedElement() but no luck.

Any idea?


Solution

  • Simply handle the KeyDown event for the textboxes and set focus there. Since you're using Tab, let the control know you'll handle it by setting e.Handled = true, which will stop the default tab action of jumping to the control with the next TabIndex.

    private void tb_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Tab)
        {
            e.Handled = true;
            LastControl.Focus();
        }
    }