You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让WPF TextBox双击选中含点分隔的完整字符串(如i.a.)

SpellCheck.CustomDictionaries 仅作用于拼写检查逻辑,和TextBox的双击选词规则属于完全独立的功能模块,所以无法通过该配置修改选词行为。

你可以通过拦截双击事件、自定义选词边界规则实现需求,以下是可直接运行的实现代码:

基础实现(单TextBox使用)

首先在XAML中为TextBox绑定双击事件:

<TextBox MouseDoubleClick="TextBox_MouseDoubleClick">Reason for contact: i.a.</TextBox>

后台C#事件处理逻辑:

private void TextBox_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    if (sender is not TextBox textBox) return;
    // 屏蔽默认的选词逻辑
    e.Handled = true;

    // 获取鼠标点击位置对应的字符索引
    int clickPosition = textBox.GetCharacterIndexFromPoint(e.GetPosition(textBox), true);
    if (clickPosition < 0 || clickPosition >= textBox.Text.Length) return;

    string rawText = textBox.Text;
    // 仅将空白类字符作为单词分隔符,点、下划线等均算单词内部字符
    char[] wordSeparators = new[] { ' ', '\t', '\n', '\r' };

    // 向左查找当前单词的起始边界
    int startIndex = clickPosition;
    while (startIndex > 0 && !wordSeparators.Contains(rawText[startIndex - 1]))
    {
        startIndex--;
    }

    // 向右查找当前单词的结束边界
    int endIndex = clickPosition;
    while (endIndex < rawText.Length && !wordSeparators.Contains(rawText[endIndex]))
    {
        endIndex++;
    }

    // 选中匹配到的整段内容
    textBox.Select(startIndex, endIndex - startIndex);
}

全局复用方案

如果需要项目中所有TextBox都遵循该选词规则,可以继承TextBox重写OnMouseDoubleClick方法,将上述逻辑封装到自定义控件中即可,无需逐个绑定事件。

内容的提问来源于stack exchange,提问作者Jesper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:24:03