Tomas Grosup
Tomas Grosup

Reputation: 6514

WPF RichTextBox ApplyPropertyValue

I am highlighting all occurences of non-breaking space in my WPF Richtextbox. Once i find the desired textrange, i call:

textrange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.DarkRed);

And it works fine. However if the highlighting occurs at the end of the document, all new typed text is highlighted as well, which is bad. Has anyone a clue how to fix this?

The complete code:

private void HighLightNonbreakSpace()
    {
        var start = this.Document.ContentStart;
        char nonBreakSpace = System.Convert.ToChar(160);
        while (start != null && start.CompareTo(this.Document.ContentEnd) < 0)
        {
            if (start.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
            {
                var match = start.GetTextInRun(LogicalDirection.Forward).IndexOf(nonBreakSpace);
                if (match >=0)
                {
                    var matchPos = start.GetPositionAtOffset(match, LogicalDirection.Forward);
                    var textrange = new TextRange(matchPos, matchPos.GetPositionAtOffset(1,LogicalDirection.Forward));
                    textrange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.DarkRed);
                    start = textrange.End;
                }
            }
            start = start.GetNextContextPosition(LogicalDirection.Forward);
        }
    }

Upvotes: 3

Views: 2159

Answers (1)

hbarck
hbarck

Reputation: 2944

You probably have to not only highlight the nbsps, but also to un-highlight everything else, i.e. add an else branch to your routine. By default, newly typed text will get its attributes from whatever is before it, so you will have to find out whether the last typed character is nbsp or not and set its properties accordingly.

Upvotes: 3

Related Questions