1

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.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632

2 Answers2

4

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.

  • 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 Weitzhandler Sep 19 '10 at 23:09
  • It's very odd, why isn't the tb visible at the expanded event?? – Shimmy Weitzhandler Sep 19 '10 at 23:12
  • 1
    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. –  Sep 20 '10 at 09:21
  • This worked for me nicely. Might not be the cleanest way, but after a couple of hours of frustration it looks like the perfect, cleanest and most beautiful solution everrrr...eeeeeeeverrr #okNot :D – OscarRyz May 29 '12 at 22:54
0

This answer solved my issue easily:

<TextBox Text="{Binding Title}"
  FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>
Community
  • 1
  • 1
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
  • For some reason this didn't work for me, the effect was to have the expander automatically expanded but the textbox didn't have the focus. I tried @fmunkert solution and worked well. :) – OscarRyz May 29 '12 at 22:53