0

I am trying to create a Side menu in wpf as shown in the image...

menu

The menu is binded to an ObservableCollection (MenuList) of the class

public class MenuItemModel
{
    public int MenuID { get; set; }
    public string MenuName { get; set; }          
    public ObservableCollection<MenuItemModel> SubMenuList { get; set; }
}

The Xaml I have been using for two level,

<ItemsControl ItemsSource="{Binding MenuList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <RadioButton x:Name="Menu"
                             Tag="{Binding MenuID}"
                             GroupName="MainMenu"                                 
                             Style="{StaticResource MenuButtonStyle}"
                             Content="{Binding MenuName}"
                             Height="30"/>
                <ListBox x:Name="SubMenu" ItemsSource="{Binding SubMenuList}"/>                   
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

It works perfectly for two levels. But I am unable to figure out how to implement third level menus (like version1, version2 in the image)? Is there any way to do this in the xaml without changing Data Models?

mapuna
  • 33
  • 5
  • Hello, i think this [link](https://stackoverflow.com/questions/45956672/wpf-binding-of-nested-menu-items) help you perfect. – NEBEZ Nov 17 '22 at 09:36
  • add ListBox.ItemTemplate with a similar DataTemplate – ASh Nov 17 '22 at 09:52
  • 1
    You probably want to use the TreeView for this job. It's a specialized ItemsControl to display hierarchical data (like your menu). You can style the TreeView to give the nodes your custom look. – BionicCode Nov 17 '22 at 12:09
  • 1
    A menuitem is a headereditemscontrol just like a treeviewitem so I don't see why you couldn't use a menu with hierarchicaldatetemplates. Like here https://stackoverflow.com/questions/51681812/binding-a-command-to-hierarchicaldatatemplate-menuitem – Andy Nov 17 '22 at 15:46
  • 1
    You can of course follow the suggestion of @Andy but you should know that Menuitem has a different behavior (layout and interaction). From your sketch it looks like you want the TreeView. Menuitem for example expands on mouse hover and it expands to the side and immediately collapses when the mouse leaves or an item received a click. It has a different layout to present the hierarchical structure. Of course you can template it to look like a TreeViewIten but then why the hassle. A Menu looks and behaves different than a TreeView. But you can customize both to adjust to requirements. – BionicCode Nov 18 '22 at 05:08
  • TreeView worked perfectly. Thank you guys for the suggestion. Now I am just trying to style TreeViewItems to look like the image. – mapuna Nov 18 '22 at 07:21

0 Answers0