我尝试了下面的代码来在聚焦时选择文本框中的所有文本。但这是行不通的。
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;
}
我也尝试过异步。冲浪很多,但是没有用。 请提出建议?
答案 0 :(得分:4)
您可以使用调度程序:
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox textBox = (TextBox)sender;
textBox.Dispatcher.BeginInvoke(new Action(() => textBox.SelectAll()));
}
答案 1 :(得分:3)
在App.xaml文件中
<Application.Resources>
<Style TargetType="TextBox">
<EventSetter Event="GotKeyboardFocus" Handler="TextBox_GotKeyboardFocus"/>
</Style>
</Application.Resources>
在App.xaml.cs文件中
private void TextBox_GotKeyboardFocus(Object sender, KeyboardFocusChangedEventArgs e)
{
TextBox tb = (TextBox)sender;
tb.Dispatcher.BeginInvoke(new Action(() => tb.SelectAll()));
}
使用此代码,您可以访问应用程序中的所有TextBox