AvaloniaUI/Avalonia · error · ArgumentOutOfRangeException

AncestorLevel may not be set to less than 1.

Error message

AncestorLevel may not be set to less than 1.

What it means

RelativeSource.AncestorLevel selects which ancestor (1 = nearest) to find in FindAncestor mode. Levels below 1 are nonsensical (there is no zeroth/negative ancestor), so the setter throws ArgumentOutOfRangeException to fail fast on invalid input.

Source

Thrown at src/Avalonia.Base/Data/RelativeSource.cs:87

        public RelativeSource(RelativeSourceMode mode)
        {
            Mode = mode;
        }

        /// <summary>
        /// Gets the level of ancestor to look for when in <see cref="RelativeSourceMode.FindAncestor"/>  mode.
        /// </summary>
        /// <remarks>
        /// Use the default value of 1 to look for the first ancestor of the specified type.
        /// </remarks>
        public int AncestorLevel
        {
            get { return _ancestorLevel; }
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(value), "AncestorLevel may not be set to less than 1.");
                }

                _ancestorLevel = value;
            }
        }

        /// <summary>
        /// Gets the type of ancestor to look for when in <see cref="RelativeSourceMode.FindAncestor"/>  mode.
        /// </summary>
        public Type? AncestorType { get; set; }

        /// <summary>
        /// Gets or sets a value that describes the type of relative source lookup.
        /// </summary>
        public RelativeSourceMode Mode { get; set; }

        public TreeType Tree { get; set; } = TreeType.Visual;
    }

View on GitHub (pinned to 11c5427268)

Solutions

  1. Use AncestorLevel >= 1 (1 = first ancestor of AncestorType).
  2. Clamp the source value: `relativeSource.AncestorLevel = Math.Max(1, computedLevel);`.
  3. Fix XAML to a positive integer for AncestorLevel.

Example fix

// before:
rs.AncestorLevel = 0; // throws

// after:
rs.AncestorLevel = 1; // nearest ancestor
Defensive patterns

Strategy: validation

Validate before calling

relativeSource.AncestorLevel = Math.Max(1, level);

Type guard

static bool IsValidLevel(int n) => n >= 1;

Prevention

When it happens

Trigger: Setting `relativeSource.AncestorLevel = 0` or any negative value. Binding it from a source that yields <=0.

Common situations: Off-by-one when computing ancestor levels dynamically. Defaulting a numeric variable to 0 then assigning it to AncestorLevel. XAML with AncestorLevel=0 by typo.

Related errors


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