Textbox SelectAll on tab but not mouse click

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

    Have not seen any clean solution so far sadly, one thing you could do is just check the mouse state:

    var tb = (TextBox)sender;
    if (Mouse.LeftButton != MouseButtonState.Pressed)
        tb.SelectAll();
    

    But there actually is a better way, as the focus shifts on key down you can check the keyboard instead. I would recommend using the proper signature for the GotKeyboardFocus handler to get the appropriate event-args:

    private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        if (e.KeyboardDevice.IsKeyDown(Key.Tab))
            ((TextBox)sender).SelectAll();
    }
    

    At this point you may still see some selection getting cleared upon click but that is just because the previous selection only gets hidden if unfocused. You can always clear the selection in LostKeyboardFocus to prevent that (e.g. ((TextBox)sender).Select(0, 0)).

提交回复
热议问题