Reputation: 2230
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.
Upvotes: 1
Views: 774
Reputation: 132548
You are binding to ContextMenu.ItemsSource
which is a different property than ContextMenu.Items
ItemsSource
will only be set if you set it to something, such as a collection of objects, and if that is the case then your ItemsControl
will also be bound to the same collection of objects. Unless the list of objects used in your ItemsSource
is bound to has a property called Icon
, your code will not work.
If you try to bind to ContextMenu.Items
, you will get a collection of MenuItem
objects, however UI objects can only have a single parent at a time, so your MenuItems
can only exist in either your ContextMenu
or your ItemsControl
, 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 the Icon
property, and return a collection of the images to display. It should be noted that this won't work until your ContextMenu
is opened the first time because the MenuItems
are not actually rendered until needed.
<ItemsControl ItemsSource="{Binding ElementName=MyObjectWithContextMenu,
Converter={StaticResource MyConverter}}" />
where MyConverter
takes the object passed to it, gets the object's ContextMenu
, loops through each MenuItem
in ContextMenu.Items
, stores a copy of the Icon
property in a List<T>
, then returns the List.
Upvotes: 1