WPF ContextMenu ItemTemplate - dynamic submenu issue

53 Views Asked by At
<ContextMenu x:Key="OverviewListViewSingleSelectionContextMenu">
    <MenuItem Name="ViewPhotosMenuItem" Header="View Photos" Click="ViewPhotosMenuItem_Click"/>
    <Separator/>
    <MenuItem Name="NavigateBackMenuItem" Header="Navigate Back">
        <ItemsControl Name="RecentAthletesItemsControl" ItemsSource="{Binding RecentAthletesContextMenuItems}">                
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <MenuItem Header="{Binding CurrentName.Fullname, Mode=OneWay}" Tag="{Binding .}" Click="RecentAthletesMenuItem_Click"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </MenuItem>
    <Separator/>
    <MenuItem Name="AutoSetAttributesMenuItem" Header="Auto-Set Attributes" Click="AutoSetAttributesMenuItem_Click"/>
</ContextMenu>

I want to add a submenu (NavigateBackMenuItem) to a context menu in WPF. The MenuItems of the submenu shall be bound to a list (RecentAthletesContextMenuItems).

That works in general fine, but the UI behaviour of the submenu is broken. I guess it is the same root cause pointed out in that post

WPF ContextMenu itemtemplate, menuitem inside menuitem

Unforunately I cannot match the solution to my problem since that does not refer to a submenu. Any help is very welcome.

1

There are 1 best solutions below

0
Norbert On

The issue with the code above is, that when you open the submenu, all menu items are marked blue and the menu is not align. Same issue as in the linked post. I found a solution that works

<ContextMenu x:Key="OverviewListViewSingleSelectionContextMenu">
    <MenuItem Name="ViewPhotosMenuItem" Header="View Photos" Click="ViewPhotosMenuItem_Click"/>
    <Separator/>

    <MenuItem Header="Navigate Back" ItemsSource="{Binding RecentAthletesContextMenuItems}">
        <MenuItem.ItemTemplate>
             <HierarchicalDataTemplate DataType="{x:Type dm:DataModel}">
                <TextBlock Text="{Binding CurrentName.ReverseFullname}" MouseDown="RecentAthletesMenuItem_Click" Tag="{Binding .}" />
            </HierarchicalDataTemplate>
        </MenuItem.ItemTemplate>
    </MenuItem>
 </ContextMenu>