{"record":{"id":"60d99656419155be","repo":"dotnet/wpf","slug":"sr-textpointer","errorCode":null,"errorMessage":"SR.TextPointer_CannotInsertTextElementBecauseItBelongsToAnotherTree","messagePattern":"SR\\.TextPointer_CannotInsertTextElementBecauseItBelongsToAnotherTree","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/TextPointer.cs","lineNumber":1391,"sourceCode":"        /// Throws ArgumentException is textElement is not valid\n        /// according to flow schema.\n        /// </exception>\n        /// <exception cref=\"InvalidOperationException\">\n        /// Throws InvalidOperationException if textElement cannot be inserted\n        /// at this position because it belongs to another tree.\n        /// </exception>\n        internal void InsertTextElement(TextElement textElement)\n        {\n            Invariant.Assert(textElement != null);\n\n            _tree.EmptyDeadPositionList();\n            SyncToTreeGeneration();\n\n            ValidationHelper.ValidateChild(this, textElement, nameof(textElement));\n\n            if (textElement.Parent != null)\n            {\n                throw new InvalidOperationException(SR.TextPointer_CannotInsertTextElementBecauseItBelongsToAnotherTree);\n            }\n            textElement.RepositionWithContent(this);\n        }\n\n        /// <summary>\n        /// Insert a paragraph break at this position by splitting all elements upto its paragraph ancestor.\n        /// </summary>\n        /// <returns>\n        /// When this position has a paragraph parent, this method returns a\n        /// normalized position in the beginning of a second paragraph.\n        ///\n        /// Otherwise, if the position is not parented by a paragraph\n        /// (for special insertion positions such as table row end, BlockUIContainer boundaries, etc),\n        /// this method creates a paragraph by using rules of EnsureInsertionPosition()\n        /// and returns a normalized position at the start of the paragraph created.\n        /// </returns>\n        /// <exception cref=\"InvalidOperationException\">\n        /// Throws InvalidOperationException when this position has a non-splittable ancestor such as Hyperlink,","sourceCodeStart":1373,"sourceCodeEnd":1409,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/TextPointer.cs#L1373-L1409","documentation":"TextPointer.InsertTextElement validates, via ValidationHelper.ValidateChild and an explicit Parent check, that the TextElement being inserted is new (unparented). If textElement.Parent != null — the element already belongs to another tree (or another position in this one) — it throws InvalidOperationException(SR.TextPointer_CannotInsertTextElementBecauseItBelongsToAnotherTree). A TextElement can live in exactly one tree.","triggerScenarios":"Calling InsertTextElement (via TextPointer.Insert, TextElementCollection.Add/Insert, InsertEmbeddedObject/UIElement wrappers, or InsertLineBreak-style helpers) with an element instance that is already parented — e.g. re-inserting a Run/UIElement that was removed from one document into another, or moving an element without detaching it.","commonSituations":"Moving a Run or embedded UIElement from one FlowDocument/RichTextBox to another; caching element instances and reusing them after the document was reloaded; cloning documents by reusing child elements instead of deep-copying.","solutions":["Ensure the element is detached first (remove it from its current parent/collection) before inserting.","Create a new element instance (or deep copy) rather than reusing the parented one.","If moving between documents, use TextRange/clipboard-based copy APIs or manually reparent: sourceCollection.Remove(element) then target InsertTextElement."],"exampleFix":"// before\ntargetPointer.InsertTextElement(run); // run.Parent != null\n// after\nif (run.Parent is TextElementCollection<Run> col) col.Remove(run);\n((IAddChild)run.Parent)?. // or:\nrun.RepositionWithContent(null); // detach, then\ntargetPointer.InsertTextElement(run);","handlingStrategy":"validation","validationCode":"if (textElement.Parent != null)\n{\n    // detach first\n    if (textElement.Parent is TextElement p) /* remove from p */;\n    else if (textElement.Parent is IAddChild) /* remove from container collection */;\n}","typeGuard":"bool CanInsert(TextElement e) => e != null && e.Parent == null;","tryCatchPattern":"try { pointer.InsertTextElement(element); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"another tree\")) { /* clone or detach and retry */ }","preventionTips":["Always Remove an element from its current collection before reinserting","Deep-copy elements when moving content between documents","Never cache and reuse parented TextElement instances"],"tags":["wpf","textelement","tree-membership"],"backgroundTag":"invalid-state-transition","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-21T21:30:21.729Z"}