从代码隐藏中聚焦时如何选择 WPF TextBox 中的所有文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16023079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:36:32  来源:igfitidea点击:

How to select all text in a WPF TextBox when focused from codebehind?

wpftextboxselectiononfocus

提问by Marc

I would like to set the focus of a WPF TextBoxfrom codebehind (not the TextBox's codebehind, but some parent control) and select all text in the TextBoxfrom the TextBoxs codebehind when it receives that focus.

我想TextBox从代码隐藏(不是代码TextBox隐藏,而是一些父控件)设置 WPF 的焦点,并在收到焦点时TextBoxTextBoxs 代码隐藏中选择所有文本。

I focus the TextBoxlike this:

我的重点是TextBox这样的:

var scope = FocusManager.GetFocusScope(txt);
FocusManager.SetFocusedElement(scope, txt);

and listen to the event in the TextBoxlike this in the TextBoxs codebehind:

TextBoxTextBoxs 代码隐藏中以这样的方式收听事件:

AddHandler(GotFocusEvent, new RoutedEventHandler(SelectAllText), true);

and try to select the text like this:

并尝试选择这样的文本:

private static void SelectAllText(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox != null)
            textBox.SelectAll();
    }

But the text doesn't get selected. How can I modify this to work as I'd like it to?

但是文本没有被选中。我怎样才能修改它以按照我的意愿工作?

回答by sa_ddam213

You will have to set Keyboardfocus on the TextBoxbefore selecting the text

在选择文本之前,您必须将Keyboard焦点设置在TextBox

Example:

例子:

private static void SelectAllText(object sender, RoutedEventArgs e)
{
    var textBox = e.OriginalSource as TextBox;
    if (textBox != null)
    {
        Keyboard.Focus(textBox);
        textBox.SelectAll();
    }    
}