Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 323
Marc Avatar asked Apr 15 '13 19:04

Marc


1 Answers

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();
    }    
}
like image 109
sa_ddam213 Avatar answered Oct 26 '22 23:10

sa_ddam213