Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly apply backgroundcolor on a text in RichTextBox

internal string Select(RichTextBox rtb, int index, int length)
    {
        TextRange textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);

        if (textRange.Text.Length >= (index + length))
        {
            TextPointer start = textRange.Start.GetPositionAtOffset(index, LogicalDirection.Forward);
            TextPointer end = textRange.Start.GetPositionAtOffset(index + length, LogicalDirection.Backward);
            rtb.Selection.Select(start, end); 
            rtb.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.LightBlue)); 
        }
        return rtb.Selection.Text;
    } 

whenever ApplyPropertyValue is called to change the backgroundcolor of selected text, it works great for the first time but it does not properly adjust the background color of the selected text segment on the second time it is called. I suspect this has to do with offsets of the document somehow being messed up after the function has been called.

What is a good way to fix this?

like image 802
l46kok Avatar asked Feb 20 '23 10:02

l46kok


1 Answers

Try this (it needs a logic a bit more complex then yours), otherwise yes: you have problems with offsets!

private static TextPointer GetTextPointAt(TextPointer from, int pos)
{
        TextPointer ret = from;
        int i = 0;

        while ((i < pos) && (ret != null))
        {
            if ((ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.Text) || (ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.None))
                i++;

            if (ret.GetPositionAtOffset(1, LogicalDirection.Forward) == null)
                return ret;

            ret = ret.GetPositionAtOffset(1, LogicalDirection.Forward);
        }

        return ret;
}

internal string Select(RichTextBox rtb, int offset, int length, Color color)
{
        // Get text selection:
        TextSelection textRange = rtb.Selection;

        // Get text starting point:
        TextPointer start = rtb.Document.ContentStart;

        // Get begin and end requested:
        TextPointer startPos = GetTextPointAt(start, offset);
        TextPointer endPos = GetTextPointAt(start, offset + length);

        // New selection of text:
        textRange.Select(startPos, endPos);

        // Apply property to the selection:
        textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(color));

        // Return selection text:
        return rtb.Selection.Text;
}

And then use it in this way (I'm selecting from first character to the fifth in RED) :

this.Select(this.myRichTextBox, 0, 5, Colors.Red);
like image 98
MAXE Avatar answered Apr 27 '23 13:04

MAXE