I have an Expander that its content consists of a StackPanel that contains several elements one of whom is a TextBox.
I want, that when the Expander expands that TextBox should gain keyboard focus, how do I do this?
I tried:
Private Sub xp_Expanded(sender As Object, e As RoutedEventArgs) _
Handles xpUnits.Expanded
stackPanel.Focus()
Keyboard.Focus(textBox)
textBox.Focus()
End Sub
I even tried to set FocusManager.IsFocusable and FocusManager.FocusedElement to the TextBox, then call stackPanel.Focus(), but it didn't do the job.
Probably your
TextBoxis not yet visible when you try to set the focus. You should add an event handler forIsVisibleChangedto yourTextBoxand set the focus there. Insidexp_Expandedyou just should set a boolean flag that theTextBoxshould be focused the next time theIsVisibleChangedevent handler is called.