3

I'm having a hard time getting this to work, and I'm hopelessly confused with all the templates one needs to use. Here's the situation.

I want to have a menu dynamically created. The code takes a list of objects, groups the list, and then sets the itemsource of the menu.

navBarControl.NavBarMain.ItemsSource = newActions.GroupBy(Function(p) p.GroupName)

I need help with the templating and databinding in XAML. What I'm looking to happen is to have a menu created with the top items being the group key, and then the children for each key being the items themselves.

And then I need to have a click handler set for every child so that I can execute code on a menu item click.

This is proving to be difficult for me to accomplish. Can some one provide a XAML example of how this would work?

Matt
  • 6,264
  • 10
  • 54
  • 82

1 Answers1

2

After some experimentation and a little luck I've finally found a solution. I hope this helps anyone else with this problem. To recap, I wanted to bind to a datasource (grouped), that has children (possibly grandchildren), and have the menu dynamically built. The challenge was routing ALL the menu item click events to a single event handler. Here's what I came up with.

<!-- Common handler for ALL menu items. This was a tough one to figure out since I kept thinking this had to be done the template somehow -->
    <Menu MenuItem.Click="navView_Click" >
        <Menu.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding}">
                <!-- Content presenter for the list of IGrouping objects. Binding is done to the Key property on the IGrouping class -->
                <ContentPresenter Content="{Binding Path=Key}"></ContentPresenter>
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <!-- Content presenter for the list of objects in each grouping. Binding is done to the Name property on the custom class -->
                        <ContentPresenter Content="{Binding Path=Name}"></ContentPresenter>
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </Menu.ItemTemplate>
    </Menu> 

And here is the itemsource being set in the code. C# and VB respectively

navBarControl.NavBarMain.ItemsSource = newActions.GroupBy(Function(p) p.GroupName)

navBarControl.NavBarMain.ItemsSource = newActions.GroupBy( p => p.GroupName);
Matt
  • 6,264
  • 10
  • 54
  • 82