AvaloniaUI/Avalonia · error · InvalidOperationException

The Control already has a parent.

Error message

The Control already has a parent.

What it means

Error "The Control already has a parent." thrown in AvaloniaUI/Avalonia.

Source

Thrown at src/Avalonia.Base/StyledElement.cs:465

        {
            value = null;
            return (_resources?.TryGetResource(key, theme, out value) ?? false) ||
                   (_styles?.TryGetResource(key, theme, out value) ?? false);
        }

        /// <summary>
        /// Sets the styled element's logical parent.
        /// </summary>
        /// <param name="parent">The parent.</param>
        void ISetLogicalParent.SetParent(ILogical? parent)
        {
            var old = Parent;

            if (parent != old)
            {
                if (old != null && parent != null)
                {
                    throw new InvalidOperationException("The Control already has a parent.");
                }

                if (InheritanceParent == null || parent == null)
                {
                    InheritanceParent = parent as AvaloniaObject;
                }

                Parent = (StyledElement?)parent;

                if (_logicalRoot != null)
                {
                    var e = new LogicalTreeAttachmentEventArgs(_logicalRoot, this, old!);
                    OnDetachedFromLogicalTreeCore(e);
                }

                var newRoot = FindLogicalRoot(this);

                if (newRoot is object)

View on GitHub (pinned to 11c5427268)

Solutions

  1. Remove the control from its current parent's child collection before adding it to a new parent.
  2. Verify logic that moves controls between panels so the control is detached first.

When it happens

Trigger: Raised when a control that already has a logical parent is added to another logical tree. Defend by removing the control from its existing parent first and checking LogicalParent before re-parenting.

Common situations: See trigger scenarios.


AI-assisted analysis of AvaloniaUI/Avalonia@11c5427268 (2026-08-13). Data as JSON: /api/errors/72067cffda27f165. Report an issue: GitHub.