Textbox SelectAll on tab but not mouse click

后端 未结 5 926
情深已故
情深已故 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:39

    I searched a lot for the solution, I found couple of solutions to selectall But, the issue is when we do right click and do cut/copy after selecting part of text from text box, it selects all even I selected part of text. To fix this here is the solution. Just add the below code in the keyboard select event. This worked for me.

        private static void SelectContentsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is TextBox)
            {
                TextBox textBox = d as TextBox;
                if ((e.NewValue as bool?).GetValueOrDefault(false))
                {
                    textBox.GotKeyboardFocus += OnKeyboardFocusSelectText;                 
                }
                else
                {
                    textBox.GotKeyboardFocus -= OnKeyboardFocusSelectText;
    
                }
            }
        }
    
    
        private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (e.KeyboardDevice.IsKeyDown(Key.Tab))
                ((TextBox)sender).SelectAll();
        }
    

提交回复
热议问题