Set the focus on a textbox in xaml wpf

后端 未结 9 1020
走了就别回头了
走了就别回头了 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 01:03

    Usage: local:FocusManager.FocusOnLoad="True"

        public class FocusManager
        {
            public static readonly DependencyProperty FocusOnLoad = DependencyProperty.RegisterAttached(
                "FocusOnLoad",
                typeof(bool),
                typeof(FocusManager),
                new UIPropertyMetadata(false, new PropertyChangedCallback(OnValueChanged))
                );
    
            private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
            {
                if (!(sender is Control control))
                    return;
    
                if ((bool) e.NewValue == false)
                    return;
    
                control.Loaded += (s, e) => control.Focus();
            }
    
            public static bool GetFocusOnLoad(DependencyObject d) => (bool) d.GetValue(FocusOnLoad);
    
            public static void SetFocusOnLoad(DependencyObject d, bool value) => d.SetValue(FocusOnLoad, value);
        }
    

提交回复
热议问题