AvaloniaUI/Avalonia · error · InvalidOperationException

Container cannot be added as a nested style.

Error message

Container cannot be added as a nested style.

What it means

Error "Container cannot be added as a nested style." thrown in AvaloniaUI/Avalonia.

Source

Thrown at src/Avalonia.Base/Styling/ContainerQuery.cs:63

        /// </summary>
        public string? Name
        {
            get => _name;
            set => _name = value;
        }

        /// <summary>
        /// Returns a string representation of the container.
        /// </summary>
        /// <returns>A string representation of the container.</returns>
        public override string ToString() => Query?.ToString(this) ?? "ContainerQuery";

        internal override void SetParent(StyleBase? parent)
        {
            if (parent is ControlTheme)
                base.SetParent(parent);
            else
                throw new InvalidOperationException("Container cannot be added as a nested style.");
        }

        internal SelectorMatchResult TryAttach(StyledElement target, object? host, FrameType type)
        {
            _ = target ?? throw new ArgumentNullException(nameof(target));

            var result = SelectorMatchResult.NeverThisType;

            if (HasChildren)
            {
                var match = Query?.Match(target, Parent, true, Name) ??
                    (target == host ?
                        SelectorMatch.AlwaysThisInstance :
                        SelectorMatch.NeverThisInstance);

                if (match.IsMatch)
                {
                    Attach(target, match.Activator, type, true);

View on GitHub (pinned to 11c5427268)

Solutions

  1. Move the ContainerQuery to a top-level Styles collection instead of nesting it inside another style.
  2. Use a regular Style with a container query selector if conditional styling is required.

When it happens

Trigger: Raised when a ContainerQuery is nested inside another style. Defend by declaring container queries only at the top level of a Styles collection and validating style trees before applying them.

Common situations: See trigger scenarios.


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