0

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

enter image description here

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.

erotavlas
  • 4,274
  • 4
  • 45
  • 104
  • Possible duplicate of [How to color different words with different colors in a RichTextBox while a user is writing and raise an event when that colored text is clicked](https://stackoverflow.com/questions/48352623/how-to-color-different-words-with-different-colors-in-a-richtextbox-while-a-user) – Harsh May 08 '18 at 17:38
  • @Harsh please remove duplicate flag, that's winforms, this is wpf – erotavlas May 08 '18 at 17:39
  • https://stackoverflow.com/questions/29316449/highlighting-keywords-in-a-richtextbox-in-wpf Did you try this solution? – Harsh May 08 '18 at 17:41
  • I think this is already answered here: https://stackoverflow.com/questions/11874800/change-style-of-selected-text-in-richtextbox – o_weisman May 08 '18 at 18:50
  • @Harsh I think this is the closest I could find https://stackoverflow.com/q/2565783/1462656 – erotavlas May 08 '18 at 19:23

0 Answers0