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
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)
).