AvaloniaUI/Avalonia · error · InvalidOperationException

Cannot create ElementName binding when NameScope is null

Error message

Cannot create ElementName binding when NameScope is null

What it means

ElementName bindings resolve the named element through the current INameScope (the XAML namescope). ReflectionBinding.CreateSourceNode throws when ElementName is set but no NameScope is available, because there is no registry to look the name up in. This typically means the binding was created outside a XAML/visual-tree context that owns a namescope.

Source

Thrown at src/Avalonia.Base/Data/ReflectionBinding.cs:198

                stringFormat: StringFormat,
                targetProperty: targetProperty,
                targetNullValue: TargetNullValue,
                targetTypeConverter: TargetTypeConverter.GetReflectionConverter(),
                updateSourceTrigger: trigger);
        }

        private INameScope? GetNameScope()
        {
            INameScope? result = null;
            NameScope?.TryGetTarget(out result);
            return result;
        }

        private ExpressionNode? CreateSourceNode(AvaloniaProperty? targetProperty)
        {
            if (!string.IsNullOrEmpty(ElementName))
            {
                var nameScope = GetNameScope() ?? throw new InvalidOperationException(
                    "Cannot create ElementName binding when NameScope is null");
                return new NamedElementNode(nameScope, ElementName);
            }

            if (RelativeSource is not null)
                return ExpressionNodeFactory.CreateRelativeSource(RelativeSource);

            return ExpressionNodeFactory.CreateDataContext(targetProperty);
        }

        private (BindingMode, UpdateSourceTrigger) ResolveDefaultsFromMetadata(
            AvaloniaObject target,
            AvaloniaProperty? targetProperty)
        {
            var mode = Mode;
            var trigger = UpdateSourceTrigger == UpdateSourceTrigger.Default ?
                UpdateSourceTrigger.PropertyChanged : UpdateSourceTrigger;

View on GitHub (pinned to 11c5427268)

Solutions

  1. Apply the binding after the element is in the visual tree so a namescope is available.
  2. Ensure the XAML defining the named element is loaded (namescope registered) before the binding resolves.
  3. Prefer CompiledBindings over ReflectionBinding so ElementName resolution uses the compiled namescope graph.
  4. If building in code, supply/attach an INameScope (NameScope.SetNameScope) containing the named element.

Example fix

// before (binding before namescope ready):
var b = new ReflectionBinding("ElementName=MyOther") { /*...*/ };
detachedControl.Bind(SomeControl.SomeProperty, b); // NameScope null -> throws

// after (apply once in tree):
this.AttachedToVisualTree += (s, e) =>
    this.Bind(SomeControl.SomeProperty, b);
Defensive patterns

Strategy: validation

Validate before calling

if (string.IsNullOrEmpty(binding.ElementName) is false && GetNameScope() is null)
    throw new InvalidOperationException("ElementName binding needs a namescope.");

Type guard

static bool HasNameScope(INameScope? ns) => ns is not null;

Prevention

When it happens

Trigger: Creating a ReflectionBinding with ElementName set and applying it where no INameScope is registered (e.g. on a detached object, or constructed in code without a namescope). Also when NameScope is a WeakReference whose target has been collected.

Common situations: Setting an ElementName binding in code-behind on an element not yet in the visual/logical tree. Binding before the template's namescope is applied. Weak reference to the namescope being garbage-collected.

Related errors


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