Reputation: 4488
There seems to be many variations of this question, but none that deal with my scenario.
I have a UserControl that is used in several places. The control has a context menu, but some of its parents also have context menus. The parent context menus are not databound, i.e. they look like this:
<ContextMenu>
<MenuItem Header="Do Something" Click="DoSomethingMenuItem_Click" />
</ContextMenu>
I can walk up the logical tree and find the parent context menu, but I can't find a way to duplicate the MenuItems (I have to duplicate them because they are only allowed one parent).
I think I am asking a very similar question to this one: https://stackoverflow.com/questions/4177298/how-to-merge-wpf-contextmenus But it has not been answers so I'm still searching!
Please don't suggest I data bind the parent control and use composite collections - there are too many places this is used to make that feasable!
Upvotes: 2
Views: 1250
Reputation: 19885
Honestly WPF has no direct way to merge context menus (rather menuitems) from the visual / logical tree of controls.
One way yu can acheive it is instead of setting the direct context menu property of your control, implement an attached property say MergedContextMenu which will be of type context menu.
Now in the property changed event...
Use the following code for Clone method....
public static UIElement cloneElement(UIElement orig){
if (orig == null)
return (null);
string s = XamlWriter.Save(orig);
StringReader stringReader = new StringReader(s);
XmlReader xmlReader = XmlTextReader.Create(stringReader, new XmlReaderSettings());
return (UIElement)XamlReader.Load(xmlReader);
}
Upvotes: 1
Reputation: 2519
Add the MenuItems from each original ContextMenu to a temporary list object, remove them from the original ContextMenus Items collection, and then add them all to the new ContextMenu. So long as the MenuItems are not contained on more than one ContextMenu at once you will be fine.
Upvotes: 0