tags:

views:

10

answers:

1

I have a list of Customer objects, which I've grouped on Country.

var query = 
    from c in ctx.Customers group c by c.Country
    ...

query is now an enumeration of groups (IQueryable<IGrouping<string, Customer>>), where each item of thie enumeration defines a group (IGrouping<string, Customer>).

I understand that IGrouping is: the key of the group (Country in my example) and the items grouped by Country. It's straightforward how to iterate through this data with a foreach statement, but what I need help on is how to bind the grouping in XAML.

I would like to use nested <ItemsControl> controls, the outer one to list the Country names and an inner one to iterate through the grouped customers for that country. By problem lies with binding to an IGrouping group.

Can it be done and if so, would the binding syntax look like?

A: 

You can use a HierarchicalDataTemplate. For instance, if you want to bind a TreeView to the result, you can do something like that :

<TreeView ItemsSource="{Binding Groups}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding}">
            <TextBlock Text="{Binding Key}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>
Thomas Levesque
Can a HierarchicalDataTemplate work containers other than a TreeView? i.e. an ItemsControl or ListBox?
eponymous23
No, it's only for controls derived from `HeaderedItemsControl`. If you want to use another kind of `ItemsControl`, use a regular `DataTemplate` that contains an `ItemsControl` for group items
Thomas Levesque