title: How to select all text in a WPF TextBox when focused from codebehind?
body: <p>I would like to set the focus of a WPF <code>TextBox</code> from codebehind (not the <code>TextBox</code>'s codebehind, but some parent control) and select all text in the <code>TextBox</code> from the <code>TextBox</code>s codebehind when it receives that focus.</p>
  
  <p>I focus the <code>TextBox</code> like this:</p>
  
  <pre><code>var scope = FocusManager.GetFocusScope(txt);
  FocusManager.SetFocusedElement(scope, txt);
  </code></pre>
  
  <p>and listen to the event in the <code>TextBox</code> like this in the <code>TextBox</code>s codebehind:</p>
  
  <pre><code>AddHandler(GotFocusEvent, new RoutedEventHandler(SelectAllText), true);
  </code></pre>
  
  <p>and try to select the text like this:</p>
  
  <pre><code>private static void SelectAllText(object sender, RoutedEventArgs e)
      {
          var textBox = e.OriginalSource as TextBox;
          if (textBox != null)
              textBox.SelectAll();
      }
  </code></pre>
  
  <p>But the text doesn't get selected. How can I modify this to work as I'd like it to?</p>