AvaloniaUI/Avalonia · error · InvalidOperationException

ControlThemes cannot be added as a nested style.

Error message

ControlThemes cannot be added as a nested style.

What it means

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

Source

Thrown at src/Avalonia.Base/Styling/ControlTheme.cs:38

        /// </summary>
        /// <param name="targetType">The value for <see cref="TargetType"/>.</param>
        public ControlTheme(Type targetType) => TargetType = targetType;

        /// <summary>
        /// Gets or sets the type for which this control theme is intended.
        /// </summary>
        public Type? TargetType { get; set; }

        /// <summary>
        /// Gets or sets a control theme that is the basis of the current theme.
        /// </summary>
        public ControlTheme? BasedOn { get; set; }

        public override string ToString() => TargetType?.Name ?? "ControlTheme";

        internal override void SetParent(StyleBase? parent)
        {
            throw new InvalidOperationException("ControlThemes cannot be added as a nested style.");
        }

        internal SelectorMatchResult TryAttach(StyledElement target, FrameType type)
        {
            Debug.Assert(type is FrameType.Theme or FrameType.TemplatedParentTheme);

            _ = target ?? throw new ArgumentNullException(nameof(target));

            if (TargetType is null)
                throw new InvalidOperationException("ControlTheme has no TargetType.");

            using var activity = Diagnostic.AttachingStyle()?
                .AddTag(Diagnostic.Tags.Style, this);
            
            if (HasSettersOrAnimations && TargetType.IsAssignableFrom(target.StyleKey))
            {
                Attach(target, null, type, true);
                activity?.AddTag(Diagnostic.Tags.SelectorResult, SelectorMatchResult.AlwaysThisType);

View on GitHub (pinned to 11c5427268)

Solutions

  1. Move the ControlTheme into a resource dictionary or the Application's themes instead of nesting it in another style.
  2. Reference the theme from the control via the Theme property rather than nesting it.

When it happens

Trigger: Raised when a ControlTheme is added as a nested style inside another style. Defend by assigning ControlTheme via the Theme property of the control instead of nesting it in Styles.

Common situations: See trigger scenarios.


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