I want to show myElement.ContextMenu icons in separate panel.
I’m trying to do this:
<ItemsControl ItemsSource="{Binding ElementName=myElement, Path=ContextMenu.ItemsSource}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type MenuItem}">
<Image Source="{Binding Icon}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
But it shows me collection of MenuItems instead of Images. How can I do it without any ViewModels and manipulations in xxx.xaml.cs file.
You are binding to
ContextMenu.ItemsSourcewhich is a different property thanContextMenu.ItemsItemsSourcewill only be set if you set it to something, such as a collection of objects, and if that is the case then yourItemsControlwill also be bound to the same collection of objects. Unless the list of objects used in yourItemsSourceis bound to has a property calledIcon, your code will not work.If you try to bind to
ContextMenu.Items, you will get a collection ofMenuItemobjects, however UI objects can only have a single parent at a time, so yourMenuItemscan only exist in either yourContextMenuor yourItemsControl, and not both.One possible option to do what you want is bind using a Converter, which will take the objects inside your
ContextMenu, and make a copy of theIconproperty, and return a collection of the images to display. It should be noted that this won’t work until yourContextMenuis opened the first time because theMenuItemsare not actually rendered until needed.where
MyConvertertakes the object passed to it, gets the object’sContextMenu, loops through eachMenuIteminContextMenu.Items, stores a copy of theIconproperty in aList<T>, then returns the List.