开发者

Unable to set focus of an element

开发者 https://www.devze.com 2023-01-17 05:39 出处:网络
I have an Expander that its content consists of a StackPanel that contains several elements one of whom is a TextBox.

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开发者_如何学Python the job.


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.


This answer solved my issue easily:

<TextBox Text="{Binding Title}"
  FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消