WPF MenuItem children not showing

I am using ObjectDataProvider and DataTemplate to populate the MenuItem inside my menu bar. (WPF, C # / XAML) See Snipet below.

Result: the top menu item appears, when I click on it, the wrap menu item appears (the one that has the associated title text), as well as a small arrow indicating the presence of children, but the children do not show the hang or click on the arrow; cannot be accessed.

Expected result: children are visible and behave correctly.

Excerpt:

<ObjectDataProvider x:Key="Brokers" ObjectInstance="{x:Static brokers:BrokerManager.Instance}" MethodName="GetBrokers" IsAsynchronous="True" /> <DataTemplate x:Key="BrokerMenuItem" DataType="IBroker"> <MenuItem Header="{Binding Path=Name}"> <MenuItem Header="Connect" /> <MenuItem Header="Disconnect" /> </MenuItem> </DataTemplate> <MenuItem Header="Brokers" ItemsSource="{Binding Source={StaticResource Brokers}}" ItemTemplate="{DynamicResource BrokerMenuItem}"/> 
+4
source share
3 answers

After searching for over a week, I finally found how to make this work properly. Turns out DataTemplates don't work too well for dynamic menus. The right way to do this is to use the ItemContainerStyle property for MenuItem. (Or is it an ItemStyleContainer?)

Just create a style to override the title and customize it for everything you need. I redefined them ItemsSource to include my children. However, be careful, as children inherit the style, and each of them has the same children and generates a recursive menu. You need to redefine your children’s ItemsSource and set it to an empty x: Array or whatever you like.

There are several blogs that describe how to use ItemContainerStyle, check them out.

0
source

arsenmrkt: I have exactly the same problem if I populate MenuItem using a DataTemplate. I cannot add children to any of these generated elements. I do not understand your answer, but how should I use ContentPresenter to get around this?

EDIT: Actually, my problem wasn’t quite the same as I am trying to associate a collection of collections with a menu. I think I started working using the HierarchicalDataTemplate:

 <Menu> <MenuItem Header="{Binding Name}" ItemsSource="{Binding MenuOptions}"> <MenuItem.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Categories}"> <MenuItem Header="{Binding Name}"/> <HierarchicalDataTemplate.ItemTemplate> <DataTemplate> <MenuItem Header="{Binding Name}"/> </DataTemplate> </HierarchicalDataTemplate.ItemTemplate> </HierarchicalDataTemplate> </MenuItem.ItemTemplate> </MenuItem> </Menu> 

Does this help you NicholasF?

+1
source

The ItemSource property of the menuitem control is used to provide children for this element, try using <ContentPresenter /> with this datatemplate.

0
source

All Articles