How to select all text in a WPF TextBox when focused from codebehind?

Marc picture Marc · Apr 15, 2013 · Viewed 10.1k times · Source

I would like to set the focus of a WPF TextBox from codebehind (not the TextBox's codebehind, but some parent control) and select all text in the TextBox from the TextBoxs codebehind when it receives that focus.

I focus the TextBox like this:

var scope = FocusManager.GetFocusScope(txt);
FocusManager.SetFocusedElement(scope, txt);

and listen to the event in the TextBox like this in the TextBoxs codebehind:

AddHandler(GotFocusEvent, new RoutedEventHandler(SelectAllText), true);

and try to select the text like this:

private static void SelectAllText(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox != null)
            textBox.SelectAll();
    }

But the text doesn't get selected. How can I modify this to work as I'd like it to?

Answer

sa_ddam213 picture sa_ddam213 · Apr 16, 2013

You will have to set Keyboard focus on the TextBox before selecting the text

Example:

private static void SelectAllText(object sender, RoutedEventArgs e)
{
    var textBox = e.OriginalSource as TextBox;
    if (textBox != null)
    {
        Keyboard.Focus(textBox);
        textBox.SelectAll();
    }    
}