tui-cs/Terminal.Gui · error · InvalidOperationException

SubViews of Margin are not supported.

Error message

SubViews of Margin are not supported.

What it means

MarginView is the outermost adornment of a View and only accepts ShadowView as a SubView. Adding any other view type throws because the margin is a strictly controlled structural element, not a general-purpose container.

Source

Thrown at Terminal.Gui/ViewBase/View.Hierarchy.cs:221

        ArgumentOutOfRangeException.ThrowIfGreaterThan (index, InternalSubViews.Count);

        //Debug.Assert (view.SuperView is null, $"{view} already has a SuperView: {view.SuperView}.");
        if (view.SuperView is { })
        {
            Logging.Warning ($"{view} already has a SuperView: {view.SuperView}.");
        }

        //Debug.Assert (!InternalSubViews.Contains (view), $"{view} has already been Added to {this}.");
        if (InternalSubViews.Contains (view))
        {
            Logging.Warning ($"{view} has already been Added to {this}.");
        }

        if (this is MarginView)
        {
            if (view is not ShadowView)
            {
                throw new InvalidOperationException ("SubViews of Margin are not supported.");
            }
        }

        if (!RaiseSubViewAdding (view))
        {
            return null;
        }

        // TODO: Make this thread safe
        InternalSubViews.Insert (index, view);

        // Try to set the SuperView - this may be cancelled
        if (!view.SetSuperView (this))
        {
            InternalSubViews.RemoveAt (index);

            // The change was cancelled
            return null;

View on GitHub (pinned to 2e47b11478)

Solutions

  1. Add the view to the main View body or to a FrameView/Window, not to Margin.
  2. If you need a shadow effect, add a ShadowView to the Margin explicitly.
  3. Check 'view is MarginView' before calling Add in generic/adornment-traversal code.

Example fix

// before
someView.Margin.Add(myLabel);
// after
someView.Add(myLabel);
Defensive patterns

Strategy: type-guard

Validate before calling

if (target is not MarginView) container.Add (child);

Type guard

static bool CanAcceptSubView (View host, View child) => host is not MarginView || child is ShadowView;

Prevention

When it happens

Trigger: Calling margin.Add(someView), view.Margin.Add(someView), or AddAt on a MarginView instance with anything other than a ShadowView.

Common situations: Mistaking the Margin adornment for a regular container; trying to draw decorations inside the margin programmatically; generic traversal code that recurses into all SubViews and tries to re-add them.

Related errors


AI-assisted analysis of tui-cs/Terminal.Gui@2e47b11478 (2026-08-13). Data as JSON: /api/errors/9e213e71dcb09640. Report an issue: GitHub.