How do I bind data to IGrouping in WPF?

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

I want to create a dynamically generated menu. The code takes a list of objects, a group list, and then sets the source of the menu items.

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

      

I need help with templates and data binding in XAML. What I'm looking for is to create a menu where the top items are the group key and then the children for each key are the items themselves.

And then I need to set up a click handler for each child so that I can execute the code when the menu item is clicked.

This turned out to be difficult for me. Can anyone provide a XAML example how this would work?

+3


source to share


1 answer


After some experimentation and a little luck, I finally found a solution. Hope this helps someone else with this problem. As a reminder, I wanted to bind to a data source (grouped) that has children (possibly grandchildren) and have a dynamically built menu. The challenge was to route ALL of the menu items that raise events for 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 this is where the data source is set in code. C # and VB respectively

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

navBarControl.NavBarMain.ItemsSource = newActions.GroupBy( p => p.GroupName);

      

+2


source







All Articles