This is a migrated thread and some comments may be shown as answers.

Restore caret position, selection, and vertical scroll position

1 Answer 281 Views
RichTextEditor
This is a migrated thread and some comments may be shown as answers.
Mihajlo
Top achievements
Rank 1
Iron
Mihajlo asked on 05 Sep 2018, 04:21 PM

Suppose I add from code some text to a shown document, like this:

try
{
    radRichTextEditor1.Document.History.IsEnabled = false;
 
    var editor = new RadDocumentEditor(radRichTextEditor1.Document);
 
    editor.Document.CaretPosition.MoveToLastPositionInDocument();
    editor.InsertParagraph();
    editor.Insert("XYZ");
 
    editor.Document.CaretPosition.MoveToFirstPositionInDocument();
 
    editor.Insert("ABC");
    editor.InsertParagraph();
}
finally
{
    radRichTextEditor1.Document.History.IsEnabled = true;
}

 

This code will destroy document's CaretPosition, Selection, and also user's view to the document (vertical scroll bar location). Is there a way to restore them to previous values?

 

1 Answer, 1 is accepted

Sort by
0
Accepted
Boby
Telerik team
answered on 10 Sep 2018, 01:48 PM
Hello Mihajlo,

You can try to use what we call "tracking" document position, for example:
double originalOffset = radRichTextEditor1.VerticalOffset;
double originalY = this.radRichTextBox.Document.CaretPosition.Location.Y;
using (DocumentPosition originalCaretPosition = new DocumentPosition(this.radRichTextBox.Document.CaretPosition, true))
{
    try
    {
        radRichTextEditor1.Document.History.IsEnabled = false;
 
        var editor = new RadDocumentEditor(radRichTextEditor1.Document);
 
        editor.Document.CaretPosition.MoveToLastPositionInDocument();
        editor.InsertParagraph();
        editor.Insert("XYZ");
 
        editor.Document.CaretPosition.MoveToFirstPositionInDocument();
 
        editor.Insert("ABC");
        editor.InsertParagraph();
    }
    finally
    {
        radRichTextEditor1.Document.History.IsEnabled = true;
    }
 
    radRichTextEditor1.Document.CaretPosition.MoveToPosition(originalCaretPosition);
    radRichTextEditor1.ActiveEditorPresenter.ScrollToVerticalOffset(originalOffset - originalY + this.radRichTextBox.Document.CaretPosition.Location.Y);
    this.radRichTextBox.UpdateEditorLayout();
 
    radRichTextEditor1.Focus();
}

You can use the same method to preserve the regions of the DocumentSelection (RadRichTextEditor.Document.Selection).

Regards,
Boby
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Tags
RichTextEditor
Asked by
Mihajlo
Top achievements
Rank 1
Iron
Answers by
Boby
Telerik team
Share this question
or