简体   繁体   中英

Select all text inside TextBox WPF

I don't know why my code doesn't work. I want, when an textBox is clicked in, select all text inside to edit it at whole.

My code :

private void XValue_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    ((TextBox)sender).SelectAll();
}

XAML code:

<TextBox x:Name="XValue" Text="{Binding XInitValue, StringFormat={}{0:#,0.0000}}" Width="80" VerticalAlignment="Center" PreviewMouseDown="XValue_PreviewMouseDown" ></TextBox>

The event happens, but the text is not selected

The problem is how the control is focused after the event is fired. You need to write e.Handled = true; , which prevents focus from bubbling.

private void XValue_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
     TextBox textbox = (TextBox)sender;
     textbox.Focus();
     textbox.SelectAll();
     e.Handled = true;
}

You could handle the GotKeyboardFocus event and use the dispatcher:

private void XValue_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    var textBox = ((TextBox)sender);
    textBox.Dispatcher.BeginInvoke(new Action(() =>
    {
        textBox.SelectAll();
    }));
}

Or the PreviewMouseDown event. The key is to use the dispatcher.

我尝试并发现它只有在设置数据上下文后才能工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM