dotnet/wpf · error

SR.DocumentGridVisualTreeContainsNonBorderAsFirstElement

Error message

SR.DocumentGridVisualTreeContainsNonBorderAsFirstElement

What it means

InvalidOperationException from DocumentGrid.MeasureOverride: the first visual child (the background) is not a Border, which means the control's internal visual tree was modified by external code. The throw is an integrity check that the tree DocumentGrid built is still intact.

Solutions

  1. Do not add or remove children of the DocumentGrid visual collection; treat its visual tree as internal
  2. Derive from DocumentViewerBase-level APIs instead of manipulating the DocumentGrid's children
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/MS/Internal/documents/DocumentGrid.cs:1047 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/1b666da490910e6e. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/MS/Internal/documents/DocumentGrid.cs:1047

            }

            //Determine which pages are visible at the current offset given the current constraint.
            RecalculateVisualPages(VerticalOffset, constraint);

            //Get our visual children count...
            int count = _childrenCollection.Count;

            //Now go through our child collection and measure all the pages to their sizes.
            for (int i = 0; i < count; i++)
            {
                //This should be our background.
                if (i == _backgroundVisualIndex)
                {
                    Border background = _childrenCollection[i] as Border;

                    if (background == null)
                    {
                        throw new InvalidOperationException(SR.DocumentGridVisualTreeContainsNonBorderAsFirstElement);
                    }

                    //We measure this to the size of our constraint.
                    background.Measure(constraint);
                }
                //Otherwise it's a page.
                else
                {
                    //Ensure that this is actually a DocumentGridPage.  If it is not,
                    //Then someone's been mucking with our VisualTree, so we'll throw.
                    DocumentGridPage page = _childrenCollection[i] as DocumentGridPage;

                    if (page == null)
                    {
                        throw new InvalidOperationException(SR.DocumentGridVisualTreeContainsNonDocumentGridPage);
                    }

                    //Get the cached size of this page and scale it to our current scale factor.

View on GitHub (pinned to 81131a70a4)