Search code examples
c#winui-3

Set focus on a control when Window is loaded with WinUI 3


I want to set focus to a textbox user control when the window is loaded.

I've tried putting txtLogin.Focus(FocusState.Programmatic); in the constructor

I've also tried doing something like


    void MainWindow_Activated(object sender, WindowActivatedEventArgs e)
    {
      txtLogin.Focus(FocusState.Programmatic);
    }

What am I missing?


Solution

  • Try the Loaded event:

    public MainWindow()
    {
        this.InitializeComponent();
    
        this.txtLogin.Loaded += (s, e) =>
        {
            this.txtLogin.Focus(FocusState.Programmatic);
        };
    }