tags:

views:

33

answers:

1

How to bind TreeView to the grouping collection ListCollectionView?

code cs:

ListCollectionView view=new ListCollectionView(Global._subjectCollection);
view.GroupDescriptions.Add(new PropertyGroupDescription("Fund"));
view.GroupDescriptions.Add(new PropertyGroupDescription("Cipher"));
treeView1.ItemsSource = view.Groups;

code XAML:

<TreeView>???</TreeView>
A: 

Check out Bea Stollnitz's blog entry "How do I display grouped data in a TreeView?".

You use a HierarchicalDataTemplate to present the CollectionViewGroup. The Name property will have the value of the property you grouped by, so the value of Fund or Cipher, and the Items property will have the nested group for outer groupings and the actual object for the innermost grouping. It will look something like this:

<Window.Resources>
    <!-- Template for actual object -->
    <DataTemplate x:Key="ThirdTemplate">
        <TextBlock Text="{Binding OtherData}"/>
    </DataTemplate>
    <!-- Template for Cipher groups -->
    <HierarchicalDataTemplate x:Key="SecondTemplate"
                              ItemsSource="{Binding Items}"
                              ItemTemplate="{StaticResource ThirdTemplate}">
        <TextBlock Text="{Binding Name}"/>
    </HierarchicalDataTemplate>
    <!-- Template for Fund groups -->
    <HierarchicalDataTemplate x:Key="FirstTemplate"
                              ItemsSource="{Binding Items}"
                              ItemTemplate="{StaticResource SecondTemplate}">
        <TextBlock Text="{Binding Name}"/>
    </HierarchicalDataTemplate>
</Window.Resources>
<TreeView Name="treeView1" ItemTemplate="{StaticResource FirstTemplate}"/>
Quartermeister