Today, in this article, we will learn how to populate hierarchical data in TreeView in WPF using MVVM architecture.

Let’s take an example of populating employees’ details per position per department in hierarchical pattern.

Step1 Create new project

Step2 InotifyPropertyChanged Class

Step3 Employee Class

Step4 Position Class

Step5 Department Class

We are done with our base implementation for required details with required classes. Now, we will bind a set of these implementations into a TreeView to populate data in hierarchical format.

Step6 ViewModel for a window to bind datacontext

Step7 Prepare View

Finally, complete the XAML code for MainWindow. The window will be as mentioned below.

  1. <Window x:Class="TreeViewMVVMBinding.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:local="clr-namespace:TreeViewMVVMBinding"
  7. xmlns:VM="clr-namespace:TreeViewMVVMBinding"
  8. mc:Ignorable="d"
  9. Title="MainWindow" Height="350" Width="525">
  10. <Window.DataContext>
  11. <VM:MainWindowViewModel/>
  12. </Window.DataContext>
  13. <Grid>
  14. <TreeView x:Name="MainTreeView" HorizontalAlignment="Stretch" Margin="10" VerticalAlignment="Stretch" ItemsSource="{Binding Departments}">
  15. <TreeView.ItemTemplate>
  16. <HierarchicalDataTemplate ItemsSource="{Binding Positions}" DataType="{x:Type VM:Department}">
  17. <Label Content="{Binding DepartmentName}"/>
  18. <HierarchicalDataTemplate.ItemTemplate>
  19. <HierarchicalDataTemplate ItemsSource="{Binding Employees}" DataType="{x:Type VM:Position}">
  20. <Label Content="{Binding PositionName}"/>
  21. <HierarchicalDataTemplate.ItemTemplate>
  22. <DataTemplate DataType="{x:Type VM:Employee}">
  23. <Label Content="{Binding EmployeeName}"/>
  24. </DataTemplate>
  25. </HierarchicalDataTemplate.ItemTemplate>
  26. </HierarchicalDataTemplate>
  27. </HierarchicalDataTemplate.ItemTemplate>
  28. </HierarchicalDataTemplate>
  29. </TreeView.ItemTemplate>
  30. </TreeView>
  31. </Grid>
  32. </Window>

We are done with the implementation. Run the application and check the output. It should be like the following.

WPF

Thank you. Please let me know if you have any query or concern regarding the above implementation. I hope I have explained enough for you to understand the concept.