简体   繁体   中英

Set Carret Position in RichTextBox C# WPF

I have a RichTextBox with Name = Editor ! And the following code :

 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 = ???? 

I want to set Editor.CaretPosition to be as it was before I selected and changed the text ? Doesn't work as here :

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

So how to do that ?

This should work if your plain text is transformed into formatted text:

 // 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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM