WPF and initial focus

后端 未结 12 2165
鱼传尺愫
鱼传尺愫 2020-11-29 15:59

It seems that when a WPF application starts, nothing has focus.

This is really weird. Every other framework I\'ve used does just what you\'d expect: puts initial foc

12条回答
  •  执笔经年
    2020-11-29 16:38

    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

提交回复
热议问题