I can get the exact start and end index of a selected text in a RichTextBox, but how do you do the reverse of this? Use the actual start and end index (character positions) to select the text again as a range to perform some formatting on it - like highlight the background.
Example - text selection using mouse and the highlight applied do not overlap
private void textBox_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if(this.textBox.Selection.Text.Length > 0)
highlightFromSelection(this.textBox, new SolidColorBrush(Colors.Yellow));
}
public void highlightFromSelection(RichTextBox textBox, SolidColorBrush color)
{
TextPointer docStart = textBox.Document.ContentStart;
TextPointer selectionStart = textBox.Selection.Start;
TextPointer selectionEnd = textBox.Selection.End;
TextRange start = new TextRange(docStart, selectionStart);
TextRange end = new TextRange(docStart, selectionEnd);
int indexStart = start.Text.Length;
int indexEnd = end.Text.Length;
MessageBox.Show("start: " + indexStart + " end: " + indexEnd);
ApplyHighlight(textBox, indexStart, indexEnd, color);
}
public void ApplyHighlight(RichTextBox textBox, int startIndex, int endIndex, SolidColorBrush color)
{
TextPointer docStart = textBox.Document.ContentStart;
//This code highlights the wrong part of text - its the closest I could get
//i.e. the highlighting does not overlap exactly with the original selection made
//TextPointer startPointer = docStart.GetPositionAtOffset(startIndex, LogicalDirection.Forward);
//TextPointer endPointer = docStart.GetPositionAtOffset(endIndex, LogicalDirection.Backward);
//TextRange range = new TextRange(startPointer, endPointer);
//range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
}
EDIT: I can only work with absolute character positions as determined from the highlightFromSelection() method.