I am trying to create a custom Undo/Redo manager for my RichTextBox Control. I insert a char in a Run and save the insertion position and the Run and other information in Undo Stack.
When I try to Undo, I remove the inserted char. After that I set the CaretPosition by this line of code:
CaretPosition = run.ContentStart.GetPositionAtOffset(position);
Everything is fine when I do not start a new Paragraph.
When I press enter and start a new paragraph and I want to undo, something strange happens. Let me explain more:
1- I press return and a new Paragraph is generated.
2- I call Undo.
3- It reaches the above line of code and this exception is thrown: Cannot set CaretPosition to be outside of RichTextBox.
I think this happens because run.Parent==null and not its parent paragraph (This run is on the first paragraph, I mean the paragraph which I pressed return). When I save this run into Undo Stack, Its parent is not null.
I saw the source code of ContentElement.cs (Run’s base class). It is written:
internal DependencyObject _parent;
internal DependencyObject Parent { get { return _parent; } }
How can this _parent property become null after some changes and how can I prevent this from happening?
Update
(assume I write “123” in the 1st paragraph.)
The first paragraph exists in Document.Blocks and It has a run with “123” in it. But it is a different run. Does this means that a new run is generated?! I’m really confused.
Thanks.
There is big probability that I’m wrong, but try to remove 2 last chars when it is new paragrpah. I think that you are getting this error because when you press return it inserts two characters: \r\n (carret return + new line)