5

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

我关注TextBox这样的:

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

并在s 代码隐藏中TextBox像这样收听事件:TextBox

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

并尝试选择这样的文本:

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

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

4

1 回答 1

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();
    }    
}
于 2013-04-15T22:26:28.243 回答