Highlight special word in a TextBox

时光怂恿深爱的人放手 提交于 2020-01-23 23:10:12

问题


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).

Examples as how it should look:

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


回答1:


see this question:

How to highlight portion of a Rich TextBox WPF control if there are more than 2 spaces?

and this open source control:

http://wpfsyntax.codeplex.com/




回答2:


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

        }
    }


来源:https://stackoverflow.com/questions/7388490/highlight-special-word-in-a-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!