How to select all text in TextBox WPF when focus?

前端 未结 2 1097
一整个雨季
一整个雨季 2020-12-21 17:54

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

XAML:

        

        
相关标签:
2条回答
  • 2020-12-21 18:11

    You could use the dispatcher:

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;
        textBox.Dispatcher.BeginInvoke(new Action(() => textBox.SelectAll()));
    }
    
    0 讨论(0)
  • 2020-12-21 18:11

    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

    0 讨论(0)
提交回复
热议问题