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?
Try this (it needs a logic a bit more complex then yours), otherwise yes: you have problems with offsets!
And then use it in this way (I’m selecting from first character to the fifth in RED) :