{"record":{"id":"96261a68a9d20886","repo":"HandyOrg/HandyControl","slug":"exceptionstringtable-typeconstraintviolatedexceptionmessage","errorCode":null,"errorMessage":"ExceptionStringTable.TypeConstraintViolatedExceptionMessage","messagePattern":"ExceptionStringTable\\.TypeConstraintViolatedExceptionMessage","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Shared/System.Windows.Interactivity/Behavior.cs","lineNumber":44,"sourceCode":"\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;\n        WritePostscript();\n        OnAssociatedObjectChanged();\n    }","sourceCodeStart":26,"sourceCodeEnd":62,"githubUrl":"https://github.com/HandyOrg/HandyControl/blob/2c0875ebd67326e0c67282967e3e809c69282fee/src/Shared/System.Windows.Interactivity/Behavior.cs#L26-L62","documentation":"Attach validates the incoming DependencyObject against the behavior's AssociatedType constraint. If the object is not an instance of AssociatedType (set via AssociatedTypeAttribute or the default), InvalidOperationException TypeConstraintViolatedExceptionMessage is thrown, naming the behavior type, the actual object type, and the expected type.","triggerScenarios":"Calling behavior.Attach(obj) where obj is non-null and !AssociatedType.IsInstanceOfType(obj), e.g. attaching a behavior declared for TextBox onto a Button, directly or via BehaviorCollection.ItemAdded.","commonSituations":"Applying a strongly-typed behavior (e.g. one constrained to TextBoxBase) to the wrong control in XAML or code; AssociatedTypeAttribute narrowed in a library update while existing markup still uses the old element type; generic behaviors where the constraint was forgotten after a refactor.","solutions":["Attach the behavior only to objects compatible with its AssociatedType; check AssociatedType.IsInstanceOfType(target) first.","If the wrong element type is used in XAML, move or retype the element (or use a less constrained behavior).","Update the AssociatedTypeAttribute if the constraint is overly restrictive for your usage.","Add a debug assertion in code that builds behaviors dynamically."],"exampleFix":"// before\nbutton.SetValue(Interaction.BehaviorsProperty, new BehaviorCollection { textBoxBehavior }); // throws\n// after\nif (behavior.AssociatedType.IsInstanceOfType(target))\n    target.SetValue(Interaction.BehaviorsProperty, new BehaviorCollection { behavior });","handlingStrategy":"validation","validationCode":"if (target == null || !behavior.AssociatedType.IsInstanceOfType(target))\n    throw new ArgumentException($\"{target?.GetType().Name} is not compatible with {behavior.AssociatedType.Name}\");","typeGuard":"static bool MatchesAssociatedType(Behavior b, DependencyObject o) =>\n    o != null && b.AssociatedType.IsInstanceOfType(o);","tryCatchPattern":"try { behavior.Attach(target); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"TypeConstraintViolated\")) {\n    // log the type mismatch: behavior type vs target type\n}","preventionTips":["Check AssociatedType before attaching programmatically.","Verify element types in XAML against AssociatedTypeAttribute on the behavior.","After library upgrades, re-check any narrowed type constraints.","Prefer generic behaviors so the compiler enforces the element type."],"tags":["wpf","interactivity","type-mismatch","associated-type"],"backgroundTag":"type-mismatch","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"}