{"record":{"id":"780bf0ba9972b6a8","repo":"dotnet/wpf","slug":"sr-textschema-cannotinsertcontentinthisposition-780bf0","errorCode":null,"errorMessage":"SR.TextSchema_CannotInsertContentInThisPosition","messagePattern":"SR\\.TextSchema_CannotInsertContentInThisPosition","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/TextRangeEditTables.cs","lineNumber":871,"sourceCode":"                    // Creating implicit ListItem\n                    ListItem listItem = new ListItem();\n                    listItem.Reposition(position, position);\n                    position = listItem.ContentStart;\n                    parent = position.Parent;\n                }\n\n                if (parent is LineBreak || parent is InlineUIContainer)\n                {\n                    position = ((Inline)parent).ElementStart;\n                    parent = position.Parent;\n                }\n            }\n\n            if (parent == null)\n            {\n                // This should be an Invariant.Assert\n                // This could happen only in case when unparented TextContainer contains only LineBreaks or InlineUIContainers\n                throw new InvalidOperationException(SR.TextSchema_CannotInsertContentInThisPosition);\n            }\n\n            TextPointer insertionPosition;\n            if (TextSchema.IsValidChild(/*position:*/position, /*childType:*/typeof(Inline)))\n            {\n                insertionPosition = CreateImplicitRun(position);\n            }\n            else\n            {\n                Invariant.Assert(TextSchema.IsValidChild(/*position:*/position, /*childType:*/typeof(Block)), \"Expecting valid parent-child relationship\");\n                insertionPosition = CreateImplicitParagraph(position);\n            }\n\n            return insertionPosition;\n        }\n\n        // Helper for EnsureInsertionPosition, inserts a Run element at this position.\n        private static TextPointer CreateImplicitRun(TextPointer position)","sourceCodeStart":853,"sourceCodeEnd":889,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/TextRangeEditTables.cs#L853-L889","documentation":"Thrown by CreateInsertionPositionInIncompleteContent when an insertion position cannot be created because the position's ancestor chain contains no parentable element (parent == null). Per the source comment, this only happens when an unparented TextContainer contains only LineBreaks or InlineUIContainers, so there is no valid spot to insert a Run. The library treats this as an unrecoverable structural state (the comment notes it should be an Invariant.Assert).","triggerScenarios":"Calling EnsureInsertionPosition (via TextRange edit APIs like InsertText/ApplyPropertyValue) on a TextContainer/TextEditor whose content contains only LineBreaks (newline characters) or InlineUIContainers with no parented text elements, so no Implicit Run position can be created.","commonSituations":"Programmatic TextRange edits against a TextBox/RichTextBox populated with bare newline content or custom InlineUIContainer content; editing a document fragment constructed without a parent structure; copy/paste of content stripped of Run elements.","solutions":["Ensure the target TextContainer is attached to a parent (e.g. the TextBox/RichTextBox document flow) and contains at least one element that can host an inline Run before calling insertion APIs","Inspect the document content: replace bare-only LineBreaks/InlineUIContainers with at least one Paragraph/Run so a valid insertion position exists","Use TextPointer move/normalize APIs (GetInsertionPosition / GetTextInsertionPosition) to verify a valid insertion position exists before editing","Wrap the edit in try-catch for InvalidOperationException and repair/rebuild the document content before retrying"],"exampleFix":"// before\nTextRange range = new TextRange(textBox.Document.ContentStart, textBox.Document.ContentEnd);\nrange.Text = \"\\n\\n\"; // only line breaks -> later edits cannot create insertion position\n// after\nrange.Text = \"\\n\\n\";\nif (range.End.GetTextInsertionPosition().HasValidLayout == false && IsUnparentedLineBreakOnlyContainer(textBox.Document))\n{\n    textBox.Document = BuildDocumentWithParagraph(); // ensure a Paragraph/Run exists\n}","handlingStrategy":"validation","validationCode":"static bool CanInsert(TextPointer pos) => pos.TextContainer.Parent != null && !IsOnlyLineBreaksOrUIContainers(pos.TextContainer);","typeGuard":"static bool HasParentedContent(TextEditor editor) => editor?.TextContainer?.Parent != null && editor.TextContainer.Start.GetNextContextPosition(LogicalDirection.Forward) != null;","tryCatchPattern":"try { range.InsertText(text); } catch (InvalidOperationException ex) when (ex.Message.Contains(\"CannotInsertContent\")) { RebuildDocumentHost(); }","preventionTips":["Keep at least one Paragraph/Run in edited documents","Verify TextPointer.GetInsertionPosition validity before edits","Test programmatic edits against newline-only and InlineUIContainer-only content"],"tags":["wpf","texteditor","invalid-state"],"backgroundTag":"internal-invariant-violation","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"}