I have read a few blog posts on this subject in my frustration to get this to work, but after playing around with this, I've figured out a way to select all text in a WPF textbox when you first click into it.
In my case, I have a TextBox and a ComboBox inside a WPF UserControl. My first instinct was to use the following code:
private void ValueBox_GotFocus(object sender, RoutedEventArgs e)
This works fine when you are purely using tabs, but what if the user actually clicks on the text box? Answer: it doesn't work.
After reading a few blog posts (especially this one
by Eric Burke
), and after trying different event handlers, I came to the following conclusions:
1. You need to use the PreviewMouseLeftButtonDown event. This is fired early enough, so that it will fire whether you select the text box with the I-beam or the Arrow. Also, if you have any context menus (which pop up via right-click), this leaves them alone.
2. The "handled" event argument needs to be set to "true", in order to keep from routing to the event that de-selects your text after you select it.
3. You need to set the Keyboard focus inside your handler. Otherwise, you won't be able to do anything inside your textbox (since execution will no longer automatically set the Keyboard focus).
So here's the code:
private void ValueBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
this._hasfocus = true;
e.Handled = true;
My control has a context menu associated with this text box, and it works just fine using this solution.