Search code examples
c#wpftabindextabstop

reset or disable/enable curent used TabIndex -runtime- to start with 1 again


I have a TextBox (firstItem) and a Button (anotherItem) on my WpfWindow, indexed with e.g. 1 and 23 (for the sake of simplicity).

So when I click the Button (that has TabIndex="23"), I want, that it resets the curent TabIndex so that the TextBox is Focused. Is that even possible?

I tried:

  • to disable and anable TabStop of Button (in ClickEvent) but no result.

could it help, if I use a function that is executed after the ClickEvent?


Solution

  • You have 2 options:

    • Focus the TextBox in CS file (non-MVVM way):

    XAML file:

    <TextBox Name="TextBoxFirst"></TextBox> <Button Click="Button_Click"></Button>

    CS file:

    private void Button_Click(object sender, RoutedEventArgs e) { TextBoxFirst.Focus(); }

    • Focus the TextBox in XAML (MVVM way):

    XAML file:

    <TextBox Name="TextBoxFirst" FocusManager.IsFocusScope="{Binding FocusOnFirstTextBox}"></TextBox>

    CS file:

    FocusOnFirstTextBox = true;

    • Bonus:

    You can access the TextBox without knowing it's name. Visual visual=YourGridName; for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++) { Visual childVisual = (Visual) VisualTreeHelper.GetChild(visual, i); if (childVisual is TextBox) { TextBox tempTextBox = childVisual as TextBox; if(tempTextBox.IsVisible) { tempTextBox.Focus(); } } }