views:

57

answers:

1

Hello!

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.

+1  A: 

Probably your TextBox is not yet visible when you try to set the focus. You should add an event handler for IsVisibleChanged to your TextBox and set the focus there. Inside xp_Expanded you just should set a boolean flag that the TextBox should be focused the next time the IsVisibleChanged event handler is called.

fmunkert
It works, but isn't there a more elegant way to do this the xaml way, or not having to add handlers for this IsVisible property of the TextBox?
Shimmy
It's very odd, why isn't the tb visible at the expanded event??
Shimmy
The TextBox is not yet visible, because at the time when the `Expanded` event handler runs, the TextBox is still in the process of being made visible. Instead of a IsVisibleChanged event handler you can use something like `Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(Window1.SetFocusToTextBoxAsync), textBox);` which is likely to run after the TextBox has become visible.
fmunkert