{"record":{"id":"9614bc4d63f3839d","repo":"dotnet/wpf","slug":"0-can-only-host-a-1-or-a-2-3-is-an-invalid-container","errorCode":null,"errorMessage":"'{0}' can only host a '{1}' or a '{2}'. '{3}' is an invalid container.","messagePattern":"'(.+?)' can only host a '(.+?)' or a '(.+?)'\\. '(.+?)' is an invalid container\\.","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/MenuItem.cs","lineNumber":2101,"sourceCode":"        /// <summary> Create or identify the element used to display the given item. </summary>\n        protected override DependencyObject GetContainerForItemOverride()\n        {\n            object currentItem = _currentItem;\n            _currentItem = null;\n\n            if (UsesItemContainerTemplate)\n            {\n                DataTemplate itemContainerTemplate = ItemContainerTemplateSelector.SelectTemplate(currentItem, this);\n                if (itemContainerTemplate != null)\n                {\n                    object itemContainer = itemContainerTemplate.LoadContent();\n                    if (itemContainer is MenuItem || itemContainer is Separator)\n                    {\n                        return itemContainer as DependencyObject;\n                    }\n                    else\n                    {\n                        throw new InvalidOperationException(SR.Format(SR.InvalidItemContainer, this.GetType().Name, nameof(MenuItem), nameof(Separator), itemContainer));\n                    }\n                }\n            }\n\n            return new MenuItem();\n        }\n\n        /// <summary>\n        ///     Called when the parent of the Visual has changed.\n        /// </summary>\n        /// <param name=\"oldParent\">Old parent or null if the Visual did not have a parent before.</param>\n        protected internal override void OnVisualParentChanged(DependencyObject oldParent)\n        {\n            base.OnVisualParentChanged(oldParent);\n            UpdateRole();\n\n            // Windows OS bug:1988393; DevDiv bug:107459\n            // MenuItem template contains ItemsPresenter where Grid.IsSharedSizeScope=\"true\" and need to inherits PrivateSharedSizeScopeProperty value","sourceCodeStart":2083,"sourceCodeEnd":2119,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/MenuItem.cs#L2083-L2119","documentation":"MenuItem validates its item containers: only MenuItem and Separator are legal children, since menu item containers must be menu items or separators. When the container resolution path encounters a container of any other type, it throws InvalidOperationException naming the host type, the two allowed types, and the offending container's type.","triggerScenarios":"Adding a non-MenuItem/non-Separator object (raw string, Button, TextBlock, custom control) to MenuItem.Items; or data-binding ItemsSource without an ItemContainerStyle/ItemContainerTemplate so the generated container is not a MenuItem, causing the check 'itemContainer is MenuItem || itemContainer is Separator' to fail.","commonSituations":"Binding MenuItem.ItemsSource to plain view-model objects without a container mapping; placing Label/Button/TextBlock children directly inside a MenuItem in XAML; custom control templates that generate foreign containers.","solutions":["Add only MenuItem or Separator children; convert other objects into MenuItems (set Header for text).","When data-binding, supply ItemContainerStyle or an ItemContainerTemplate so each data item is wrapped in a MenuItem.","Put arbitrary content inside MenuItem.Header instead of adding it as a direct child item.","If you need specialized containers, derive them from MenuItem so the type check passes."],"exampleFix":"// before: menuItem.Items.Add(new Button { Content = \"Click\" }); // throws // after: menuItem.Items.Add(new MenuItem { Header = \"Click\" });","handlingStrategy":"type-guard","validationCode":"static bool IsValidMenuItemChild(object item) => item is MenuItem || item is Separator;","typeGuard":"bool IsMenuContainer(DependencyObject c) => c is MenuItem || c is Separator;","tryCatchPattern":"try { menuItem.Items.Add(child); } catch (InvalidOperationException ex) when (ex.Message.Contains(\"invalid container\")) { menuItem.Items.Add(new MenuItem { Header = child.ToString() }); }","preventionTips":["Only add MenuItem or Separator objects to MenuItem.Items.","When binding ItemsSource to plain data, always set ItemContainerStyle/ItemContainerTemplate mapping to MenuItem.","Nest arbitrary UI inside MenuItem.Header, not as a direct item.","Derive custom menu containers from MenuItem."],"tags":["wpf","menu","menuitem","container-validation","itemscontrol"],"backgroundTag":"invalid-argument-value","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-21T21:30:21.729Z"}