WPF MVVM Focus Field on Load

后端 未结 6 2043
梦谈多话
梦谈多话 2020-12-13 01:58

I have a View that has a single TextBox and a couple Buttons below it. When the window loads I want that TextBox to have focus.

6条回答
  •  爱一瞬间的悲伤
    2020-12-13 02:43

    After having a 'WPF Initial Focus Nightmare' and based on some answers on stack, the following proved for me to be the best solution.

    First, add your App.xaml OnStartup() the followings:

    EventManager.RegisterClassHandler(typeof(Window), Window.LoadedEvent,
              new RoutedEventHandler(WindowLoaded));
    

    Then add the 'WindowLoaded' event also in App.xaml :

    void WindowLoaded(object sender, RoutedEventArgs e)
        {
            var window = e.Source as Window;
            System.Threading.Thread.Sleep(100);
            window.Dispatcher.Invoke(
            new Action(() =>
            {
                window.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
    
            }));
        }
    

    The threading issue must be use as WPF initial focus mostly fails due to some framework race conditions.

    I found the following solution best as it is used globally for the whole app.

    Hope it helps...

    Oran

提交回复
热议问题