WPF文本框在Tab键聚焦时全选

8
我想在用Tab键完成焦点后选择所有文本。但我找不到正确的解决方案。现在我正在使用GotFocusEvent,但是当我用鼠标单击时它也会触发事件。
我现在使用的代码如下:
EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText));


void SelectAllText(object sender, RoutedEventArgs e)
{
    var textBox = sender as System.Windows.Controls.TextBox;
    if (textBox != null)
        if (!textBox.IsReadOnly)
            textBox.SelectAll();
}

请查看以下答案:https://dev59.com/eGgt5IYBdhLWcg3w0wzB#11787674 - Nkosi
2个回答

8

参考这个答案

在Tab键上选择文本框但不在鼠标单击时选择全部文本

你所拥有的可以被修改为...

EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(OnGotKeyboardFocus));

void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    var textBox = sender as System.Windows.Controls.TextBox;

    if (textBox != null && !textBox.IsReadOnly && e.KeyboardDevice.IsKeyDown(Key.Tab))
        textBox.SelectAll();
}

您还需注意关于在 LostKeyboardFocus 时清除选择的细节。


1
谢谢!它可以工作了,请注意 "RoutedEventHandler(OnGotKeyboardFocus)" 应该是 "KeyboardFocusChangedEventHandler(OnGotKeyboardFocus)"。 - Alejandro Rosas
明白了,那是我的笔误。复制你的代码时忘记改了。已经修复了。 - Nkosi
1
@KyloRen,猜我们可能永远不会知道。哈哈。我给你的帖子点了赞来抵消它。:) 也因为你的帖子很相关。 - Nkosi
@Nkosi,对你的帖子点赞+1...有人在跟踪我的帖子...最近我的很多帖子都被投反对票,但是管理员又将其撤回,也许我参与的帖子也会遭受同样的负面评价... :( - Kylo Ren

1
请使用以下方式使用 MouseButtonState
 void SelectAllText(object sender, RoutedEventArgs e)
    {
        if (Mouse.LeftButton == MouseButtonState.Released)
        {
            var textBox = sender as System.Windows.Controls.TextBox;
            if (textBox != null)
                if (!textBox.IsReadOnly)
                    textBox.SelectAll();
        }
    }

1
谁在为了自己的快乐而进行投票?!至少添加评论。 - Kylo Ren
谢谢 :) 这个可以用,但也许像Nkosi的解决方案一样处理键盘会更好。 - Alejandro Rosas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接