Can't set focus to a child of UserControl

后端 未结 18 588
耶瑟儿~
耶瑟儿~ 2020-12-04 21:55

I have a UserControl which contains a TextBox. When my main window loads I want to set the focus to this textbox so I added Focusable=\"True

18条回答
  •  庸人自扰
    2020-12-04 22:38

    After trying combinations of the suggestions above, I was able to reliably assign focus to a desired text box on a child UserControl with the following. Basically, give focus to the child control and have the child UserControl give focus to its TextBox. The TextBox's focus statement returned true by itself, however did not yield the desired result until the UserControl was given focus as well. I should also note that the UserControl was unable to request focus for itself and had to be given by the Window.

    For brevity I left out registering the Loaded events on the Window and UserControl.

    Window

    private void OnWindowLoaded(object sender, RoutedEventArgs e)
    {
        ControlXYZ.Focus();
    }
    

    UserControl

    private void OnControlLoaded(object sender, RoutedEventArgs e)
    {
        TextBoxXYZ.Focus();
    }
    

提交回复
热议问题