Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to data bind a hierarchical data to a WPF TreeView?

The type looks like this:

class Category
{
    public string Name;
    public string Message;

    public ObservableCollection<Category> SubCategories;
}

where it will have say 5 categories, where each category contains subcategories between 0 (none) to say 3.

I know how to bind non-hierarchical data to a WPF TreeView, but can't figure it out for hierarchical data values.

like image 506
Joan Venge Avatar asked Nov 10 '10 23:11

Joan Venge


2 Answers

Here is an example.....

<!-- Create a TreeView, and have it source data from
       the AnimalCategories collection -->
  <TreeView ItemsSource="{x:Static local:Window1.AnimalCategories}">
 
    <!-- Specify the template that will display a node
         from AnimalCategories.  I.e., one each for “Amphibians”
         and “Spiders” in this sample.  It will get its nested
         items from the "Animals" property of each item -->
    <TreeView.ItemTemplate>
      <HierarchicalDataTemplate ItemsSource="{Binding Path=Animals}">
 
        <!-- Display the AnimalCategory by showing it's Category string -->
        <TextBlock FontWeight="Bold" Text="{Binding Path=Category}" />
 
        <!-- Specify the nested template for the individual Animal items
             that are within the AnimalCategories.  E.g. “California Newt”, etc. -->
        <HierarchicalDataTemplate.ItemTemplate>
          <DataTemplate>
            <TextBlock Text="{Binding Path=Name}"/>
          </DataTemplate>
        </HierarchicalDataTemplate.ItemTemplate>
       
      </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
  </TreeView>

this code is from here it might be more helpfull to you to read that article, i am thinking.

like image 65
Muad'Dib Avatar answered Oct 14 '22 12:10

Muad'Dib


I know this question was asked a long time ago.... but there is a very good example on MSDN that expands upon Muad'Dib's answer.

Their XAML looks like this:

    <StackPanel x:Name="LayoutRoot" Background="White">
        <StackPanel.Resources>
            <HierarchicalDataTemplate x:Key="ChildTemplate" >
                <TextBlock FontStyle="Italic" Text="{Binding Path=Title}" />
            </HierarchicalDataTemplate>
            <HierarchicalDataTemplate x:Key="NameTemplate" ItemsSource="{Binding Path=ChildTopics}" ItemTemplate="{StaticResource ChildTemplate}">
                <TextBlock Text="{Binding Path=Title}" FontWeight="Bold" />
            </HierarchicalDataTemplate>
        </StackPanel.Resources>
        <TreeView Width="400"  Height="300" ItemsSource="{Binding}" ItemTemplate="{StaticResource NameTemplate}" x:Name="myTreeView" />
    </StackPanel>

I found combining the two to work perfectly for me.

like image 44
Walter Avatar answered Oct 14 '22 12:10

Walter