简体   繁体   English

选择 TextBox WPF 中的所有文本

[英]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: XAML 代码:

<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;你需要写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:您可以处理GotKeyboardFocus事件并使用调度程序:

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

Or the PreviewMouseDown event.或者PreviewMouseDown事件。 The key is to use the dispatcher.关键是使用调度器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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