Is it possible to change a part of the text already in the RichTextBox, for example, to change the text color for this part of the text?

    1 answer 1

    Of course. You only need TextPointer for the desired text position.

    Having a TextPointer at the beginning of the text, let's select the characters from the second to the fourth:

     var range = new TextRange(start.GetPositionAtOffset(2), start.GetPositionAtOffset(4)); range.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Green); range.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow); 

    The question is how to get the beginning of the text. Here is the code:

     RichTextBox rtb = ...; FlowDocument doc = rtb.Document; TextPointer start = doc.ContentStart; 

    not quite true, since doc.ContentStart points to the beginning of FlowDocument 'a, followed by the beginning of Paragraph ' a, and only then the text. Therefore, it is probably better to do this:

     while (start != null && start.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text) start = start.GetNextContextPosition(LogicalDirection.Forward); if (start == null) // в документе нет текста, выходим 
    • @ AN90: Please! Glad if it helped. - VladD
    • I can not understand one thing. The answer, as I understand it, indicates the position of the content (not necessarily the text) in the document. Is it possible to somehow determine the position in the text fragment document if the number of the character with which it begins in the line obtained from TextRange for the entire document is known? I can not figure it out, but it is very necessary. - AN90
    • @ AN90: Wrote the answer here . - VladD