{"record":{"id":"738f83f7e21044b6","repo":"dotnet/wpf","slug":"sr-format-sr-textschema-textelementcollection","errorCode":null,"errorMessage":"SR.Format(SR.TextSchema_TheChildElementBelongsToAnotherTreeAlready, this.GetType().Name)","messagePattern":"SR\\.Format\\(SR\\.TextSchema_TheChildElementBelongsToAnotherTreeAlready, this\\.GetType\\(\\)\\.Name\\)","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/TextElementCollection.cs","lineNumber":253,"sourceCode":"        /// </param>\n        /// <param name=\"newItem\">\n        /// A TextElement to be inserted into the collection after the previousSibling.\n        /// It must be unlinked from a tree before insertion.\n        /// </param>\n        public void InsertAfter(TextElementType previousSibling, TextElementType newItem)\n        {\n            ArgumentNullException.ThrowIfNull(previousSibling);\n\n            ArgumentNullException.ThrowIfNull(newItem);\n\n            if (previousSibling.Parent != this.Parent)\n            {\n                throw new InvalidOperationException(SR.Format(SR.TextElementCollection_PreviousSiblingDoesNotBelongToThisCollection, previousSibling.GetType().Name));\n            }\n\n            if (newItem.Parent != null)\n            {\n                throw new ArgumentException(SR.Format(SR.TextSchema_TheChildElementBelongsToAnotherTreeAlready, this.GetType().Name));\n            }\n\n            ValidateChild(newItem);\n\n            this.TextContainer.BeginChange();\n            try\n            {\n                newItem.RepositionWithContent(previousSibling.ElementEnd);\n            }\n            finally\n            {\n                this.TextContainer.EndChange();\n            }\n        }\n\n        /// <summary>\n        /// Inserts a TextElement newItem into a collection before a nextSibling TextElement.\n        /// </summary>","sourceCodeStart":235,"sourceCodeEnd":271,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/TextElementCollection.cs#L235-L271","documentation":"Thrown by TextElementCollection<T>.InsertAfter as an ArgumentException when the item being inserted already has a Parent. WPF text-tree elements may belong to exactly one tree; the collection refuses to re-parent an element that is already attached anywhere.","triggerScenarios":"Calling InsertAfter(previousSibling, newItem) where newItem.Parent != null, i.e. newItem is already a child of some TextElementCollection or text tree (even a different position in the same tree).","commonSituations":"Moving a Run/Paragraph between documents without detaching it first; reusing a cached element instance; accidentally inserting the same element twice after loading XAML.","solutions":["Remove newItem from its current parent first (e.g. call Remove/RemoveAt on the owning collection, or set the property holding it to null) before InsertAfter.","Create a fresh element instance instead of reusing the existing one, copying over properties/content.","Guard the call: only invoke InsertAfter when newItem.Parent is null."],"exampleFix":"// before\nparagraph.InsertAfter(anchorRun, cachedRun); // cachedRun.Parent != null\n// after\nif (cachedRun.Parent is Paragraph owner)\n    owner.Inlines.Remove(cachedRun);\nparagraph.InsertAfter(anchorRun, cachedRun);","handlingStrategy":"validation","validationCode":"if (newItem.Parent == null)\n    collection.InsertAfter(previousSibling, newItem);","typeGuard":"bool CanInsert(TextElementType item) => item is not null && item.Parent is null;","tryCatchPattern":"try { collection.InsertAfter(prev, item); }\ncatch (ArgumentException ex) when (ex.Message.Contains(\"belongs to another tree\")) { /* detach or clone item, retry */ }","preventionTips":["Treat TextElements as single-owner: remove from old parent before re-inserting.","Never cache and reuse element instances across documents.","Prefer cloning when you need the same content in two places."],"tags":["wpf","text-tree","invalid-argument","element-already-parented"],"backgroundTag":"invalid-argument-value","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"}