Set the focus on a textbox in xaml wpf

后端 未结 9 1039
走了就别回头了
走了就别回头了 2020-11-30 00:29

Despite some posts on this forum and others i cannot find something that tells me how to set the focus on a TextBox.

I have a userControl with many labe

9条回答
  •  借酒劲吻你
    2020-11-30 00:57

    For completeness, there is also a way to handle this from code behind (e.g. in the case of controls that, for whatever reason, are created dynamically and don't exist in XAML). Attach a handler to the window's Loaded event and then use the ".Focus()" method of the control you want. Bare-bones example below.

    public class MyWindow
    {
        private VisualCollection controls;
        private TextBox textBox;
    
        // constructor
        public MyWindow()
        {
            controls = new VisualCollection(this);
            textBox = new TextBox();
            controls.Add(textBox);
    
            Loaded += window_Loaded;
        }
    
        private void window_Loaded(object sender, RoutedEventArgs e)
        {
            textBox.Focus();
        }
    }
    

提交回复
热议问题