1

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?

Michael1248
  • 150
  • 1
  • 12

1 Answers1

1

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(); } } }

Red Wei
  • 854
  • 6
  • 22
  • Thanks a lot (: First option I knew already.. but the problem is: I don't know the name of the `TextBox` AND if I would know: There are several `TextBox`'es on the screen (`Visible` and `Collapsed`). So I don't know which is the first `TextBox` to set your second option to the first `TextBox` – Michael1248 Oct 13 '16 at 08:29
  • now I search the `TextBox` relativly and set it via `Focus()`. – Michael1248 Oct 14 '16 at 09:32
  • Thanks for your 'Bonus Code'. I changed it a bit to do the work, and it did it (: – Michael1248 Oct 24 '16 at 08:35