Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all text in TextBox WPF when focused?

Tags:

c#

wpf

xaml

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?

like image 339
Srinivasan Avatar asked Nov 27 '18 13:11

Srinivasan


2 Answers

You could use the dispatcher:

private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    textBox.Dispatcher.BeginInvoke(new Action(() => textBox.SelectAll()));
}
like image 164
mm8 Avatar answered Nov 17 '22 19:11

mm8


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

like image 14
Uday Teja Avatar answered Nov 17 '22 17:11

Uday Teja