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
- Use AncestorLevel >= 1 (1 = first ancestor of AncestorType).
- Clamp the source value: `relativeSource.AncestorLevel = Math.Max(1, computedLevel);`.
- 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
- Default AncestorLevel computations to 1, not 0.
- Clamp dynamic values to >= 1.
- Validate XAML integer attributes for AncestorLevel.
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
- BindingExpression has not been started.
- Cannot call AsObservable on a to binding expression which is
- BindingExpression was already attached.
- BindingExpression was already attached to a different proper
- Cannot subscribe to IndexerDescriptor.
AI-assisted analysis of AvaloniaUI/Avalonia@11c5427268 (2026-08-13).
Data as JSON: /api/errors/5c83faececcf10ae.
Report an issue: GitHub.