WPF and initial focus

后端 未结 12 2202
鱼传尺愫
鱼传尺愫 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:26

    Based on the accepted answer implemented as an attached behavior:

    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    
    namespace UI.Behaviors
    {
        public static class FocusBehavior
        {
            public static readonly DependencyProperty FocusFirstProperty =
                DependencyProperty.RegisterAttached(
                    "FocusFirst",
                    typeof(bool),
                    typeof(FocusBehavior),
                    new PropertyMetadata(false, OnFocusFirstPropertyChanged));
    
            public static bool GetFocusFirst(Control control)
            {
                return (bool)control.GetValue(FocusFirstProperty);
            }
    
            public static void SetFocusFirst (Control control, bool value)
            {
                control.SetValue(FocusFirstProperty, value);
            }
    
            static void OnFocusFirstPropertyChanged(
                DependencyObject obj, DependencyPropertyChangedEventArgs args)
            {
                Control control = obj as Control;
                if (control == null || !(args.NewValue is bool))
                {
                    return;
                }
    
                if ((bool)args.NewValue)
                {
                    control.Loaded += (sender, e) =>
                        control.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                }
            }
        }
    }
    

    Use it like this:

    
    

提交回复
热议问题