在RichTextBox C#WPF中设置Carret位置

时间:2016-03-18 14:28:39

标签: c# wpf richtextbox rtf

我有RichTextBox Name = 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 

那怎么做?

1 个答案:

答案 0 :(得分:4)

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

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