5

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?

Marc
  • 12,706
  • 7
  • 61
  • 97
  • Are you certain that textBox is not null in your SelectAllText handler? Set a breakpoint and step through it. – Steve Apr 15 '13 at 20:08
  • You say the `TextBox`'s code behind. If your handler is an instance method of the actual TextBox, why not just call SelectAll() instead of getting the reference from the sender? – Steve Apr 15 '13 at 20:11
  • @Steve, I've checked/tried that. The text does get selected according to the selectedText property but it is not being selected in the UI, for whatever reason.. – Marc Apr 15 '13 at 20:17

1 Answers1

14

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();
    }    
}
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110