Can't set focus to a child of UserControl

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

    “When setting initial focus at application startup, the element to receive focus must be connected to a PresentationSource and the element must have Focusable and IsVisible set to true. The recommended place to set initial focus is in the Loaded event handler" (MSDN)

    Simply add a "Loaded" event handler in the constructor of your Window (or Control), and in that event handler call the Focus() method on the target control.

        public MyWindow() {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MyWindow_Loaded);
        }
    
        void MyWindow_Loaded(object sender, RoutedEventArgs e) {
            textBox.Focus();
        }
    

提交回复
热议问题