{"record":{"id":"67d2228479199e69","repo":"HandyOrg/HandyControl","slug":"exceptionstringtable-behavior","errorCode":null,"errorMessage":"ExceptionStringTable.CannotHostBehaviorMultipleTimesExceptionMessage","messagePattern":"ExceptionStringTable\\.CannotHostBehaviorMultipleTimesExceptionMessage","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Shared/System.Windows.Interactivity/Behavior.cs","lineNumber":41,"sourceCode":"            return _associatedObject;\n        }\n    }\n\n    protected Type AssociatedType\n    {\n        get\n        {\n            ReadPreamble();\n            return _associatedType;\n        }\n    }\n\n    public void Attach(DependencyObject dependencyObject)\n    {\n        if (!Equals(dependencyObject, AssociatedObject))\n        {\n            if (AssociatedObject != null)\n                throw new InvalidOperationException(ExceptionStringTable\n                    .CannotHostBehaviorMultipleTimesExceptionMessage);\n            if (dependencyObject != null && !AssociatedType.IsInstanceOfType(dependencyObject))\n                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,\n                    ExceptionStringTable.TypeConstraintViolatedExceptionMessage,\n                    new object[] { GetType().Name, dependencyObject.GetType().Name, AssociatedType.Name }));\n            WritePreamble();\n            _associatedObject = dependencyObject;\n            WritePostscript();\n            OnAssociatedObjectChanged();\n            OnAttached();\n        }\n    }\n\n    public void Detach()\n    {\n        OnDetaching();\n        WritePreamble();\n        _associatedObject = null;","sourceCodeStart":23,"sourceCodeEnd":59,"githubUrl":"https://github.com/HandyOrg/HandyControl/blob/2c0875ebd67326e0c67282967e3e809c69282fee/src/Shared/System.Windows.Interactivity/Behavior.cs#L23-L59","documentation":"A Behavior instance in System.Windows.Interactivity can be attached to only one DependencyObject at a time. Attaching it while it is already associated with another object throws InvalidOperationException with CannotHostBehaviorMultipleTimesExceptionMessage. This guards the one-to-one invariant between a behavior and its AssociatedObject.","triggerScenarios":"Calling behavior.Attach(newObject) (directly or via BehaviorCollection.ItemAdded) on a behavior whose AssociatedObject is already non-null and different from newObject.","commonSituations":"Reusing a single behavior instance across multiple controls; adding the same behavior to a second element's Interaction.Behaviors collection; a collection property-change firing twice so the same behavior is attached twice; re-attaching after forgetting the old host still holds it.","solutions":["Create a new behavior instance for each attached object instead of sharing one instance.","Detach the behavior from its current host (oldHost.Interaction.Behaviors.Remove(behavior)) before attaching it to a new object.","Check behavior.AssociatedObject == null before calling Attach.","Clear/rebuild the Behaviors collection on the previous host when moving the behavior."],"exampleFix":"// before\nvar behavior = new MyBehavior();\nelement1.SetValue(Interaction.BehaviorsProperty, new BehaviorCollection { behavior });\nelement2.SetValue(Interaction.BehaviorsProperty, new BehaviorCollection { behavior }); // throws\n// after\nelement1.SetValue(Interaction.BehaviorsProperty, new BehaviorCollection { new MyBehavior() });\nelement2.SetValue(Interaction.BehaviorsProperty, new BehaviorCollection { new MyBehavior() });","handlingStrategy":"validation","validationCode":"if (behavior.AssociatedObject != null && !ReferenceEquals(behavior.AssociatedObject, target))\n    behavior = (Behavior)Activator.CreateInstance(behavior.GetType()); // fresh instance per host\nbehavior.Attach(target);","typeGuard":"static bool CanAttach(Behavior b, DependencyObject target) =>\n    b.AssociatedObject == null && target != null && b.AssociatedType.IsInstanceOfType(target);","tryCatchPattern":"try { behavior.Attach(target); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"CannotHostBehaviorMultipleTimes\")) {\n    // create a new instance of the behavior for this host\n}","preventionTips":["Never share behavior instances between controls; one instance per host.","Remove behaviors from the old collection before adding to a new one.","Assert AssociatedObject == null in code that wires behaviors dynamically.","Be careful with data templates/styles that reuse the same collection instance."],"tags":["wpf","interactivity","invalid-state-transition","behavior"],"backgroundTag":"invalid-state-transition","analyzedSha":"2c0875ebd67326e0c67282967e3e809c69282fee","analyzedAt":"2026-09-14T14:45:29.754Z","contentChangedAt":"2026-09-14T14:45:29.754Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}