The essence of the question is as follows. After the text has been obtained from RichTextBox via TextRange.Text, you can get the substring index in the string object. Is it possible, knowing this index, to find the TextRange corresponding to this substring in the RichTextBox?

    1 answer 1

    You need this code (made on the basis of this post ):

    TextPointer FindPointerAtTextOffset(TextPointer from, int offset, bool seekStart) { if (from == null) return null; TextPointer current = from; TextPointer end = from.DocumentEnd; int charsToGo = offset; while (current.CompareTo(end) != 0) { Run currentRun; if (current.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text && (currentRun = current.Parent as Run) != null) { var remainingLengthInRun = current.GetOffsetToPosition(currentRun.ContentEnd); if (charsToGo < remainingLengthInRun || (charsToGo == remainingLengthInRun && !seekStart)) return current.GetPositionAtOffset(charsToGo); charsToGo -= remainingLengthInRun; current = currentRun.ElementEnd; } else { current = current.GetNextContextPosition(LogicalDirection.Forward); } } if (charsToGo == 0 && !seekStart) return end; return null; } 

    Explanation: In FlowDocument , you have different supporting positions: the beginning of the document, the beginning of a paragraph, the beginning of a Span 'a, etc. For these positions, you can iterate using GetNextContextPosition . Of these, all the text is only inside the Run , and the rest are official. Thus, we iterate and find all Run blocks, for each of them we get the length of the inner text and see if our position is in the current block or not.

    Use so. Suppose we want to get characters from the 5th to the 18th. We write:

     TextPointer start = FindPointerAtTextOffset(flowDocument.ContentStart, 5, seekStart: true); if (start == null) { // 5-ая позиция вне документа, выходим } TextPointer end = FindPointerAtTextOffset(start, 18 - 5, seekStart: false); if (end == null) { // 18-ая позиция вне документа, выходим } TextRange range = new TextRange(start, end); 
    • Thanks for the answer! I am trying to change the color of a piece of text through this text's TextRange. I get the starting and ending positions of the text, I create based on the positions TextRange. Set color. The color does not change for that part of the text - there is some offset. Sometimes for a piece of text, the end position is null. - AN90
    • @ AN90: Very strange, it seems to work for me. Can you give a reproducing example? - VladD
    • Text: "# 1111111111111111 # \ r \ n @ 0000000000000000 @ \ r \ n". The index of the beginning of the text fragment is 21, the fragment length is 16 characters ("0000000000000000"). - AN90