Search code examples
wpftreeviewbindingtreeviewitem

Wpf Treeview bind base on Project Folder Structure


I currently have a catalog of files I want to read into my program in my Project. Structure.

Project
   - Properties
   - References
   - Manufacturers (want to project this as treeview)
      - Honda
         - file1
         - file2
      - Toyota
         - file1
         - file2

In my program each file above is represented by its own business object. I want to be able to in my program have this in my treeview.

- Honda
     - file1
     - file2
- Toyota
     - file1
     - file2

I only load these file once so I want to just read these file once and bind them to the tree view. Is there an elegant way to do this???

Thanks, Kev


Solution

  • You can make use of a HierarchicalDataTemplate

    <toolkit:HierarchicalDataTemplate x:Key="FileTemplate" >
           <TextBlock Text="{Binding Path=FileName}" />
    </toolkit:HierarchicalDataTemplate>
    <toolkit:HierarchicalDataTemplate x:Key="ManufacturerTemplate" 
            ItemsSource="{Binding Path=Files}" 
            ItemTemplate="{StaticResource FileTemplate}">
            <TextBlock Text="{Binding Path=Name}"/>
    </toolkit:HierarchicalDataTemplate>
    
    <toolkit:TreeView ItemsSource="{Binding}" 
        ItemTemplate="{StaticResource ManufacturerTemplate}"/>
    

    Your business objects could look something like this...

    class Manufacturer
    {
         String Name {get; set;}
         ObservableCollection<File> Files {get; set;}
    
    }
    
    class File
    {
         String FileName {get; set;}
    }
    

    You would then set the DataContext of the TreeView to ObservableCollection<Manufacturer>