Sander Boonstra
Sander Boonstra

Reputation: 13

Highlighting/Coloring charactars in a wpf richtextbox

  public static void HighlightText(RichTextBox richTextBox,int startPoint,int endPoint, Color color)
    {
      //Trying to highlight charactars here
    }

Startpoint is the first character that should be highlighted and the endPoint the last one.

Have been searching the web for quiet a while now but i still haven't figured out how to solve my problem. I hope any of you knows how to solve this problem.

Upvotes: 1

Views: 488

Answers (1)

Neil B
Neil B

Reputation: 2224

Here is the general idea:

public static void HighlightText(RichTextBox richTextBox, int startPoint, int endPoint, Color color)
{
    //Trying to highlight charactars here
    TextPointer pointer = richTextBox.Document.ContentStart;
    TextRange range = new TextRange(pointer.GetPositionAtOffset(startPoint), pointer.GetPositionAtOffset(endPoint));
    range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(color));
}

However you will need to iterate through the document to get the correct text positions, since offset index number doesn't match number of characters. Some characters may represent multiple offset positions.

Here is the method that does that. I'm not aware of a way to do this without looping through the entire document.

public static void HighlightText(RichTextBox richTextBox, int startPoint, int endPoint, Color color)
{
    //Trying to highlight charactars here
    TextPointer pointer = richTextBox.Document.ContentStart;
    TextPointer start = null, end = null;
    int count = 0;
    while (pointer != null)
    {
        if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
        {
            if (count == startPoint) start = pointer.GetInsertionPosition(LogicalDirection.Forward);
            if (count == endPoint) end = pointer.GetInsertionPosition(LogicalDirection.Forward);
            count++;
        }
        pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
    }
    if (start == null) start = richTextBox.Document.ContentEnd;
    if (end == null) end = richTextBox.Document.ContentEnd;

    TextRange range = new TextRange(start, end);
    range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(color));
}

Upvotes: 1

Related Questions