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

Mar*_*arc 5 wpf textbox selection onfocus

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

我这样关注TextBox:

var scope = FocusManager.GetFocusScope(txt);
FocusManager.SetFocusedElement(scope, txt);
Run Code Online (Sandbox Code Playgroud)

TextBoxTextBoxs codebehind 中听这样的事件:

AddHandler(GotFocusEvent, new RoutedEventHandler(SelectAllText), true);
Run Code Online (Sandbox Code Playgroud)

并尝试选择如下文本:

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

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

sa_*_*213 14

在选择文本之前,您必须将Keyboard注意力集中在其上TextBox

例:

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