[英]How to select all text in TextBox WPF when focused?
I have tried the below code to select all text in textbox when focus.我已尝试使用以下代码在焦点时选择文本框中的所有文本。 But this is not working.
但这是行不通的。
XAML : XAML :
<TextBox Text="test1" Width="100" Height="200"
GotFocus="TextBox_GotFocus"></TextBox>
c#: 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?
请建议?
You could use the dispatcher:您可以使用调度程序:
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox textBox = (TextBox)sender;
textBox.Dispatcher.BeginInvoke(new Action(() => textBox.SelectAll()));
}
in App.xaml file在 App.xaml 文件中
<Application.Resources>
<Style TargetType="TextBox">
<EventSetter Event="GotKeyboardFocus" Handler="TextBox_GotKeyboardFocus"/>
</Style>
</Application.Resources>
in App.xaml.cs file在 App.xaml.cs 文件中
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使用此代码,您可以访问应用程序中的所有文本框
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.