Textbox SelectAll on tab but not mouse click

后端 未结 5 881
情深已故
情深已故 2021-01-07 22:56

So lets say I have a WPF form with several text boxes, if you tab to the text box and it already has something in it, I want to select all the text in that box so typing wil

5条回答
  •  抹茶落季
    2021-01-07 23:30

    You can use attached behavior pattern

    public class Behaviors
    {
        public static readonly DependencyProperty SelectTextOnFocusProperty = DependencyProperty
            .RegisterAttached("SelectTextOnFocus", typeof(bool), typeof(Behaviors), new FrameworkPropertyMetadata(false, GotFocus));
    
        public static void SetSelectTextOnFocus(DependencyObject obj, bool value)
        {
            obj.SetValue(SelectTextOnFocusProperty, value);
        }
    
        private static void GotFocus(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var textbox = d as TextBox;
    
            if (null == textbox) return;
    
            textbox.GotKeyboardFocus += SelectTextOnFocus;
            textbox.GotMouseCapture += SelectTextOnFocus;
        }
    
        private static void SelectTextOnFocus(object sender, RoutedEventArgs e)
        {
            if (!(sender is TextBox)) return;
            ((TextBox)sender).SelectAll();
        }
    }
    

    in your xaml only need

    xmlns:my="clr-namespace:Namespace;assembly=Rkmax"
    

    use you can use in a TextBox like

    
    

    all this work for mouse and keyboard event

提交回复
热议问题