Restore caret position, selection, and vertical scroll position

2 posts, 1 answers
  1. Mihajlo
    Mihajlo avatar
    38 posts
    Member since:
    Aug 2018

    Posted 05 Sep 2018 Link to this post

    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?

     

  2. Answer
    Boby
    Admin
    Boby avatar
    729 posts

    Posted 10 Sep 2018 Link to this post

    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.
Back to Top