Question

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?

Was it helpful?

Solution

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();
    }    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top