Can't set focus to a child of UserControl

后端 未结 18 587
耶瑟儿~
耶瑟儿~ 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:25

    I don't like solutions with setting another tab scope for UserControl. In that case, you will have two different carets when navigating by keyboard: on the window and the another - inside user control. My solution is simply to redirect focus from user control to inner child control. Set user control focusable (because by default its false):

    
    

    and override focus events handlers in code-behind:

    protected override void OnGotFocus(RoutedEventArgs e)
    {
        base.OnGotFocus(e);
        MyTextBox.Focus();
    }
    
    protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
    {
        base.OnGotKeyboardFocus(e);
        Keyboard.Focus(MyTextBox);
    }
    

提交回复
热议问题