问题
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