I am trying to highlight a row in a RichTextBox. My attempt was to get the line position in the text and then create a TextRange representing text.Substring(offset, word.Length). But for some reason, RichTextBox selects only the last 2 characters of the previous line and some characters of the actual line or only parts of the actual line. My current approach is this:
public void SelectLine(string text)
{
int i = new TextRange(editor.Document.ContentStart, editor.Document.ContentEnd).Text.IndexOf(text);
TextPointer start = editor.Document.ContentStart.GetPositionAtOffset(i);
TextPointer end = start.GetPositionAtOffset(text.Length);
TextRange r = new TextRange(start, end);
if (r != null)
{
r.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red);
r.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White);
}
}
And this is how it looks when I try to select the second row:

Do you have any idea why this is happening?
EDIT:
My current approach includes WPF RichTextBox.
source
share