焦点时如何在TextBox WPF中选择所有文本?

Sri*_*san 1 c# wpf xaml

我试过下面的代码以在聚焦时选择文本框中的所有文本。但这是行不通的。

XAML

        <TextBox Text="test1" Width="100" Height="200"  
           GotFocus="TextBox_GotFocus"></TextBox>
Run Code Online (Sandbox Code Playgroud)

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;
        } 
Run Code Online (Sandbox Code Playgroud)

我也尝试过异步。冲浪很多,但是没有用。请提出建议?

Uda*_*eja 9

在 App.xaml 文件中

<Application.Resources>
    <Style TargetType="TextBox">
        <EventSetter Event="GotKeyboardFocus" Handler="TextBox_GotKeyboardFocus"/>
    </Style>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

在 App.xaml.cs 文件中

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

使用此代码,您可以访问应用程序中的所有 TextBox


mm8*_*mm8 8

您可以使用调度程序:

private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    textBox.Dispatcher.BeginInvoke(new Action(() => textBox.SelectAll()));
}
Run Code Online (Sandbox Code Playgroud)

  • 这基本上是一个时间问题。`Dispatcher.BeginInvoke` 调度调用 `SelectAll()` 的委托在 UI 线程空闲时执行。 (2认同)