在 RichTextBox C# WPF 中设置插入符位置

Set Carret Position in RichTextBox C# WPF

我有一个 RichTextBoxName = Editor!以及以下代码:

 String textRich = new TextRange(Editor.Document.ContentStart, Editor.Document.ContentEnd).Text;           
 EditorColor ec = new EditorColor(textRich);//Transform The text in RTF Text
 Stream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(ec.SetText())); //SetText Function return a RTF text
 Editor.Selection.Select(Editor.Document.ContentStart, Editor.Document.ContentEnd);
 Editor.Document.Blocks.Clear();
 Editor.Selection.Load(stream, DataFormats.Rtf);//Change the text with the RTF Text
 Editor.CaretPosition = ???? 

我想将 Editor.CaretPosition 设置为选择和更改文本之前的状态?不像这里那样工作:

 TextPointer carret = Editor.CaretPosition;
 do above code ......
 Editor.CaretPosition = carret; // it sets the carret at end of Richtextbox 

那么怎么做呢?

如果将纯文本转换为格式化文本,这应该有效:

 // Save the current position
 int caretIntPosition = GetIntPosition(Editor.CaretPosition, Editor);

 // Do your work ...

 // Restore the position
 SetIntPosition(caretIntPosition, Editor);

 /// <summary>
 /// Converts a TextPointer position into an int position.
 /// </summary>
 int GetIntPosition(TextPointer pointerPosition, RichTextBox rtb)
 {
     int intPosition = 0;

     TextPointer currentPosition = rtb.Document.ContentStart;

     while (currentPosition.CompareTo(pointerPosition) != 0)
     {
         intPosition++;

         currentPosition = currentPosition.GetNextInsertionPosition(LogicalDirection.Forward);
     }

     return intPosition;
 }

 /// <summary>
 /// Converts an int position back into a TextPointer position and places the caret there.
 /// </summary>
 void SetIntPosition(int intPosition, RichTextBox rtb)
 {
     TextPointer currentPosition = rtb.Document.ContentStart;

     for (int i = 1; i <= intPosition; i++)
     {
         currentPosition = currentPosition.GetNextInsertionPosition(LogicalDirection.Forward);
     }

     rtb.CaretPosition = currentPosition;
 }