9

I have tried the below code to select all text in textbox when focus. But this is not working.

XAML:

        <TextBox Text="test1" Width="100" Height="200"  
           GotFocus="TextBox_GotFocus"></TextBox>

c#:

private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            (sender as TextBox).SelectAll();    
            //(sender as TextBox).Select(0, (sender as TextBox).Text.Length);
            (sender as TextBox).Focus();  
            e.Handled = true;
        } 

I have tried with asynchronous also. Surf lots , but nothing works. Please suggest?

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Srinivasan
  • 131
  • 1
  • 8
  • 1
    Duplicate `https://stackoverflow.com/questions/660554/how-to-automatically-select-all-text-on-focus-in-wpf-textbox` – Afnan Ahmad Nov 27 '18 at 13:35
  • 4
    Possible duplicate of [How to automatically select all text on focus in WPF TextBox?](https://stackoverflow.com/questions/660554/how-to-automatically-select-all-text-on-focus-in-wpf-textbox) – Antoine V Nov 27 '18 at 13:51

2 Answers2

18

You could use the dispatcher:

private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    textBox.Dispatcher.BeginInvoke(new Action(() => textBox.SelectAll()));
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • 1
    Thanks.. it's working. can you explain why we invoke the method inside the Dispatcher. Is there any specific reason for that? – Srinivasan Nov 27 '18 at 16:52
  • 3
    It's basically a timing issue. `Dispatcher.BeginInvoke` schedules the delegate that call `SelectAll()` to be executed when the UI thread is idle. – mm8 Nov 29 '18 at 15:52
17

in App.xaml file

<Application.Resources>
    <Style TargetType="TextBox">
        <EventSetter Event="GotKeyboardFocus" Handler="TextBox_GotKeyboardFocus"/>
    </Style>
</Application.Resources>

in App.xaml.cs file

private void TextBox_GotKeyboardFocus(Object sender, KeyboardFocusChangedEventArgs e)
{
    TextBox tb = (TextBox)sender;
    tb.Dispatcher.BeginInvoke(new Action(() => tb.SelectAll()));
}

With this code you reach all TextBox in your Application

H. de Jonge
  • 878
  • 7
  • 25
Uday Teja
  • 263
  • 3
  • 15