Set focus on textbox in WPF

后端 未结 9 836
-上瘾入骨i
-上瘾入骨i 2020-11-28 08:03

How to set the focus on an TextBox element in WPF

I have this code:

txtCompanyID.Focusable = true;
txtCompanyID.Focus();
9条回答
  •  一向
    一向 (楼主)
    2020-11-28 08:14

    Nobody explained so far why the code in the question doesn't work. My guess is that the code was placed in the constructor of the Window. But at this time it's too early to set the focus. It has to be done once the Window is ready for interaction. The best place for the code is the Loaded event:

    public KonsoleWindow() {
      public TestWindow() {
        InitializeComponent();
        Loaded += TestWindow_Loaded;
      }
    
      private void TestWindow_Loaded(object sender, RoutedEventArgs e) {
        txtCompanyID.Focus();
      }
    }
    

提交回复
热议问题