{"record":{"id":"0e869973cecee06f","repo":"dotnet/wpf","slug":"sr-elementmustbeinpopup-contextmenu","errorCode":null,"errorMessage":"SR.ElementMustBeInPopup (ContextMenu)","messagePattern":"SR\\.ElementMustBeInPopup \\(ContextMenu\\)","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/ContextMenu.cs","lineNumber":678,"sourceCode":"        }\n\n        private static void OnAccessKeyPressed(object sender, AccessKeyPressedEventArgs e)\n        {\n            e.Scope = sender;\n            e.Handled = true;\n        }\n\n        /// <summary>\n        /// Called when this element's visual parent changes\n        /// </summary>\n        /// <param name=\"oldParent\"></param>\n        protected internal override void OnVisualParentChanged(DependencyObject oldParent)\n        {\n            base.OnVisualParentChanged(oldParent);\n\n            if (!Popup.IsRootedInPopup(_parentPopup, this))\n            {\n                throw new InvalidOperationException(SR.Format(SR.ElementMustBeInPopup, \"ContextMenu\"));\n            }\n        }\n\n        internal override void OnAncestorChanged()\n        {\n            base.OnAncestorChanged();\n\n            if (!Popup.IsRootedInPopup(_parentPopup, this))\n            {\n                throw new InvalidOperationException(SR.Format(SR.ElementMustBeInPopup, \"ContextMenu\"));\n            }\n        }\n\n        #endregion\n\n        #region Private Fields\n\n        private Popup _parentPopup;","sourceCodeStart":660,"sourceCodeEnd":696,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/ContextMenu.cs#L660-L696","documentation":"A ContextMenu must be rooted in a Popup; WPF enforces this when the menu's visual parent changes. If OnVisualParentChanged finds the ContextMenu has gained a visual parent but is not rooted in a Popup (_parentPopup), it throws InvalidOperationException(SR.ElementMustBeInPopup). This preserves the assumption that context menus are hosted by the Popup plumbing.","triggerScenarios":"Adding a ContextMenu directly to a visual tree as a child of another element (e.g. panel.Children.Add(contextMenu) or setting it as content) so its visual parent is not a Popup.","commonSituations":"Re-parenting a ContextMenu into a Grid/Canvas in code, moving a ContextMenu between controls in a way that attaches it to the visual tree, or template scenarios that accidentally place the menu in the tree.","solutions":["Assign the ContextMenu via the ContextMenu property of an element (element.ContextMenu = menu) instead of adding it to a visual tree.","If manual display is needed, wrap in/let WPF create the Popup and call menu.IsOpen = true rather than parenting it directly.","Remove code that adds the ContextMenu as a child of a panel or window content.","If moving the menu between owners, detach from the old owner first so the visual parent does not change while un-rooted."],"exampleFix":"// before\nstackPanel.Children.Add(myContextMenu); // throws\n// after\nmyButton.ContextMenu = myContextMenu;","handlingStrategy":"validation","validationCode":"bool safe = !IsInVisualTree(myContextMenu); // only attach via ContextMenu property\nstatic bool IsInVisualTree(DependencyObject d) { DependencyObject p = d; while ((p = VisualTreeHelper.GetParent(p)) != null) return true; return false; }","typeGuard":"static bool CanAttachToVisualTree(ContextMenu m) => Popup.IsRootedInPopup(null, m); // false unless popup-managed","tryCatchPattern":"try\n{\n    panel.Children.Add(menu); // do not do this\n}\ncatch (InvalidOperationException)\n{\n    target.ContextMenu = menu; // correct attachment\n}","preventionTips":["Attach ContextMenus only via the ContextMenu property","Never add a ContextMenu to a Children/Content collection","Detach from a previous owner before reassigning"],"tags":["wpf","contextmenu","popup","visual-tree"],"backgroundTag":"invalid-state-transition","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-22T01:17:13.364Z"}