Search code examples
c#.netwpfrichtextboxcaret

How do I "restore" the Caret Position in a Wpf RichTextBox?


After setting my RichTextBox's text to the string T, the Caret Position in the RichTextBox is "lost" (it goes to the start of it). Here's what I'm doing to try to "restore" it after it is "lost":

public static int GetCaretIndex(RichTextBox C)
{
    return new TextRange(C.Document.ContentStart, C.CaretPosition).Text.Length;
}
...
int CaretIndex = GetCaretIndex(C); // Get the Caret position before setting the text of the RichTextBox
new TextRange(C.Document.ContentStart, C.Document.ContentEnd).Text = T; // Set the text of the RichTextBox
C.CaretPosition = C.Document.ContentStart.GetPositionAtOffset(CaretIndex, LogicalDirection.Forward); // Set the Caret Position based on the "Caret Index" variable

This code, however, does not work. The "restored" Caret is at a different position than the "original" one (always behind the "original" one for some reason).

"Saving" the RichTextBox's CaretPosition as a TextPointer doesn't seem to work either.

Can anyone provide me with an alternative way of "restoring" the Caret, or a way to fix the code above?


Solution

  • Seems to work (for me): C.CaretPosition = C.Document.ContentStart; C.CaretPosition = C.CaretPosition.GetPositionAtOffset(CaretIndex, LogicalDirection.Forward);

    (I hate RichTextBox by the way.)