简体   繁体   English

WPF TextBox选择Tab焦点上的所有内容

[英]WPF TextBox select all on Tab focus

I'm trying to select all the text when the focus is done with the Tab key . 我正在尝试使用Tab键完成焦点时选择所有文本。 But I'm not able to find the right solution. 但我无法找到合适的解决方案。 Now I'm using the GotFocusEvent but now when i click with the mouse it raises the event. 现在我正在使用GotFocusEvent,但现在当我用鼠标点击它时会引发事件。

The code that I'm using now is: 我现在使用的代码是:

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();
}

Referencing this answer 参考这个答案

Textbox SelectAll on tab but not mouse click 选项卡上的文本框SelectAll但不是鼠标单击

What you have can be modified to... 你有什么可以修改为......

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();
}

You should also take notice of the details about clearing the selection on LostKeyboardFocus 您还应该注意有关清除LostKeyboardFocus选择的详细信息

Use MouseButtonState as below: 使用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();
        }
    }

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

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