Home > database >  TreeView binding to List<Itemes>
TreeView binding to List<Itemes>

Time:03-03

I have a list of items, where each item in the list contains another list of items.

public List<JobesGroup> JobeGroups { get; set; } = new List<JobesGroup>() 
{
   new JobesGroup()
   {
       ID=1,
       GroupName="test1",
       Jobes=new List<Jobe>()
       {
           new Jobe()
           {
               ID=1,
               JobeName="sss"
           },
           new Jobe()
           {
               ID=2,
               JobeName="aaa"
           }
       }
   },
   new JobesGroup()
   {
       ID=2,
       GroupName="test2",
       Jobes=new List<Jobe>()
       {
           new Jobe()
           {
               ID=3,
               JobeName="ddd"
           },
           new Jobe()
           {
               ID=4,
               JobeName="fff"
           }
       }
   }
};

I want the TreeView main items to show the GroupName and the subitemes wo show the JobName. How to bind it to the TreeView?

CodePudding user response:

You have a hierarchical data structure, meaning an item contains another collection of items. A TreeView can display hierarchical data using HierarchicalDataTemplates. Such a template defines the apprearance of an item and specifies the ItemsSource for the next level. It can also define a data template for the next level explicitly by using the ItemTemplate property. This can either be a HierarchicalDataTemplate or a DataTemplate depending on the level providing hierarchical or non-hierarchical data. If no other item template is specified, the same data template will be applied to all items across all levels.

The first level are JobesGroup items and the second level are Jobes items.

  • First level: Needs an HierarchicalDataTemplate that defines how GroupName is shown and specifies the Jobes property as the ItemsSource of the next level.
  • Second level: A simple DataTemplate for JobeName is enough, since there are no more levels underneath. It defines how JobeName is displayed.
<TreeView ItemsSource="{Binding JobeGroups}">
   <TreeView.ItemTemplate>
      <HierarchicalDataTemplate DataType="{x:Type local:JobesGroup}"
                                ItemsSource="{Binding Jobes}">
         <TextBlock Text="{Binding GroupName}"/>
         <HierarchicalDataTemplate.ItemTemplate>
            <DataTemplate DataType="{x:Type local:Jobe}">
               <TextBlock Text="{Binding JobeName}"/>
            </DataTemplate>
         </HierarchicalDataTemplate.ItemTemplate>
      </HierarchicalDataTemplate>
   </TreeView.ItemTemplate>
</TreeView>
  • Related