在文本框中突出显示特殊词

问题描述:

如何突出显示文本中所有出现的单词列表. 例如,我确实有一个字符串列表("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));

        }
    }