在文本框中突出显示特殊词 [英] Highlight special word in a TextBox

查看:74
本文介绍了在文本框中突出显示特殊词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何突出显示文本中所有出现的单词列表. 例如,我确实有一个字符串列表("if","else","then","while","true"). 我确实需要在TextBox中找到它们并将其突出显示(前景+背景颜色).

How do I highlight all occurrences of a list of words in a text. For example, i do have a list of strings ("if", "else", "then", "while", "true"). I do need to find them in a TextBox and highlight them (foreground + background color).

其外观示例:

当前方法是重写TextBox并在OnTextChange事件中执行某些操作".

The current approach is to override TextBox and do "something" in the OnTextChange event.

推荐答案

我实际上正在使用一些使用RichTextBox的方法,但是我的步骤很慢. 意识到我如何标记事物仍然存在一些错误.例如,一切都会 在第一个要标记的字符之后标记.所以看起来像这样:

I'm actually using some approaches using the RichTextBox but im making steps slowly. Realized how i mark things there are still some bugs. For instance, everything gets marked after the first character to mark. So it looks just like that:

pos is the position of the character i want to mark (+1 for just one character), in OnTextChange
MarkForeground(pos + 2, pos + 2 + 1, Colors.Green); // +2 for some awkward wpf bug probably ;)

private void MarkForeground(int start, int end, Color col)
    {
        TextPointer startPointer = this.Document.ContentStart.GetPositionAtOffset(start);
        TextPointer endPointer = this.Document.ContentStart.GetPositionAtOffset(end);

        if (startPointer != null && endPointer != null)
        {

            TextRange range = new TextRange(startPointer, endPointer);


            range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(col));

        }
    }

这篇关于在文本框中突出显示特殊词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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