stride3d/stride · error · InvalidOperationException

This behavior must be attached to an instance of…

Error message

This behavior must be attached to an instance of TreeViewItem.

What it means

TreeViewStopEditOnLostFocusBehavior overrides OnAttached and validates that the AssociatedObject (the element the behavior is attached to in XAML) is a TreeViewItem. Attaching it to any other control type throws InvalidOperationException because the behavior's logic depends on TreeViewItem-specific focus/selection semantics.

Solutions

  1. Attach the behavior only to TreeViewItem elements, typically via <TreeView.ItemContainerStyle> with a Style targeting TreeViewItem containing <i:Interaction.Behaviors>
  2. Move the behavior declaration to the correct element in the XAML tree
  3. If attaching programmatically, verify AssociatedObject type before behaviors.Add

Example fix

// before
<TreeView>
  <i:Interaction.Behaviors>
    <b:TreeViewStopEditOnLostFocusBehavior/>
  </i:Interaction.Behaviors>
// after
<TreeView.ItemContainerStyle>
  <Style TargetType="TreeViewItem">
    <Setter Property="b:TreeViewStopEditOnLostFocusBehavior.EnableStopEdit" Value="True"/>
  </Style>
</TreeView.ItemContainerStyle>
Defensive patterns

Strategy: type-guard

Validate before calling

if (treeViewItem is TreeViewItem)
    ((TreeViewItem)treeViewItem).AssureBehavior<TreeViewStopEditOnLostFocusBehavior>();

Type guard

static bool CanAttachStopEdit(object o) => o is TreeViewItem;

Try / catch

try { behaviors.Add(new TreeViewStopEditOnLostFocusBehavior()); }
catch (InvalidOperationException ex) { log.Warn("Behavior attached to wrong element type", ex); }

Prevention

When it happens

Trigger: Declaring the behavior in an Interaction.Behaviors collection on an element that is not a TreeViewItem (e.g. on TreeView itself, a Grid, or a ListBoxItem).

Common situations: Copy-pasting the behavior XAML snippet onto the wrong element; attaching at the TreeView level instead of via ItemContainerStyle for the TreeViewItem containers.

Understand the failure class

Background: "is not a compatible type" / "cannot merge" errors: when a value's type doesn't match what the library requires — this error's family across 65 libraries.

Related errors


AI-assisted analysis of stride3d/stride@96fad776d2 (2026-09-14). Data as JSON: /api/errors/813636e13130335f. Report an issue: GitHub.

Appendix: source

Thrown at sources/editor/Stride.Core.Assets.Editor/View/Behaviors/TreeViewStopEditOnLostFocusBehavior.cs:19

protected override void OnAttached()
{
    if (!(AssociatedObject is TreeViewItem))
        throw new InvalidOperationException("This behavior must be attached to an instance of TreeViewItem.");
    base.OnAttached();
}

protected override void OnEvent()
{
    var treeViewItem = (TreeViewItem)AssociatedObject;
    treeViewItem.SetCurrentValue(TreeViewItem.IsEditingProperty, false);
}

View on GitHub (pinned to 96fad776d2)