如何在 WPF TextBox 中自动选择焦点上的所有文本? [英] How to automatically select all text on focus in WPF TextBox?

查看:60
本文介绍了如何在 WPF TextBox 中自动选择焦点上的所有文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我从 GotFocus 事件处理程序中调用 SelectAll,它对鼠标不起作用 - 一旦释放鼠标,选择就会消失.

If I call SelectAll from a GotFocus event handler, it doesn't work with the mouse - the selection disappears as soon as mouse is released.

人们喜欢 Donnelle 的回答,我将尝试解释为什么我不像接受的答案那样喜欢它.

People are liking Donnelle's answer, I'll try to explain why I did not like it as much as the accepted answer.

  • 它更复杂,而接受的答案以更简单的方式做同样的事情.
  • 接受答案的可用性更好.当您单击文本中间时,当您松开鼠标时,文本将被取消选择,允许您立即开始编辑,如果您仍想全选,只需再次按下按钮,这次它不会在松开时取消选择.按照 Donelle 的食谱,如果我单击文本中间,则必须第二次单击才能进行编辑.如果我点击文本内的某处而不是文本外的某处,这很可能意味着我想开始编辑而不是覆盖所有内容.

推荐答案

不知道为什么它在 GotFocus 事件中丢失了选择.

Don't know why it loses the selection in the GotFocus event.

但一种解决方案是对 GotKeyboardFocusGotMouseCapture 事件进行选择.这样它就会一直有效.

But one solution is to do the selection on the GotKeyboardFocus and the GotMouseCapture events. That way it will always work.

-- 编辑 --

在此处添加一个示例,向人们展示如何解决提到的一些缺点:

Adding an example here to show people how to work around some the mentioned drawbacks:

private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    // Fixes issue when clicking cut/copy/paste in context menu
    if (textBox.SelectionLength == 0) 
        textBox.SelectAll();
}

private void TextBox_LostMouseCapture(object sender, MouseEventArgs e)
{
    // If user highlights some text, don't override it
    if (textBox.SelectionLength == 0) 
        textBox.SelectAll();

    // further clicks will not select all
    textBox.LostMouseCapture -= TextBox_LostMouseCapture; 
}

private void TextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    // once we've left the TextBox, return the select all behavior
    textBox.LostMouseCapture += TextBox_LostMouseCapture;
}

这篇关于如何在 WPF TextBox 中自动选择焦点上的所有文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆