Build Tree View and Bind in WPF using Recursive Function

First create below class 
  1. public sealed class ItemGroup : NotifyPropertyChanged  
  2. {  
  3. private int _GPID;  
  4. public int GPID  
  5. {  
  6. get { return _GPID; }  
  7. set  
  8. {  
  9. _GPID = value;  
  10. RaiseNotifyPropertyChange("GPID");  
  11. }  
  12. }  
  13. private string _Name;  
  14. public string Name  
  15. {  
  16. get { return _Name; }  
  17. set  
  18. {  
  19. _Name = value;  
  20. RaiseNotifyPropertyChange("Name");  
  21. }  
  22. }  
  23. List<ItemGroup> _chld = new List<ItemGroup>();  
  24. public List<ItemGroup> Chld  
  25. {  
  26. get { return _chld; }  
  27. set  
  28. {  
  29. _chld = value;  
  30. RaiseNotifyPropertyChange("Chld");  
  31. }  
  32. }  
  33. }  
Create Observable Collection and initialise in constructor 
  1. public ObservableCollection<ItemGroup> Items { getset; }  
Now, fetch your data in datatable and call below methods
  1. private void BuildTree(ObservableCollection<ItemGroup> objTreeView)  
  2. {  
  3. if (dt != null)  
  4. {  
  5. foreach (DataRow dataRow in dt.Rows)  
  6. {  
  7. if (Convert.ToInt32(dataRow["GPID"]) == 0)  
  8. {  
  9. var obj = new ItemGroup();  
  10. obj.Name = dataRow["Name"].ToString();  
  11. foreach (ItemGroup childnode in GetChildNode(Convert.ToInt64(dataRow["GID"])))  
  12. {  
  13. obj.Chld.Add(childnode);  
  14. }  
  15. objTreeView.Add(obj);  
  16. }  
  17. }  
  18. }  
  19. }  
  20. private List<ItemGroup> GetChildNode(long parentid)  
  21. {  
  22. List<ItemGroup> childtreenodes = new List<ItemGroup>();  
  23. DataRow[] tmptbl = dt.Select("GPID = " + parentid);  
  24. foreach (DataRow dataRow in tmptbl)  
  25. {  
  26. ItemGroup childNode = new ItemGroup();  
  27. childNode.Name = dataRow["Name"].ToString();  
  28. foreach (ItemGroup cnode in GetChildNode(Convert.ToInt64(dataRow["GID"])))  
  29. {  
  30. childNode.Chld.Add(cnode);  
  31. }  
  32. childtreenodes.Add(childNode);  
  33. }  
  34. return childtreenodes;  
  35. }  
Now, create below window
  1. <Window x:Class="TreeView.MainWindow"  
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4. xmlns:self="clr-namespace:TreeView"  
  5. Title="MainWindow" Height="350" Width="525">  
  6. <Window.DataContext>  
  7. <self:MainWindowViewModel></self:MainWindowViewModel>  
  8. </Window.DataContext>  
  9. <Grid Margin="10">  
  10. <TreeView Grid.Row="3" Name="trbMenu" ItemsSource="{Binding Items}">  
  11. <TreeView.ItemTemplate>  
  12. <HierarchicalDataTemplate DataType="{x:Type self:ItemGroup}" ItemsSource="{Binding Chld}">  
  13. <TextBlock Text="{Binding Name}" />  
  14. </HierarchicalDataTemplate>  
  15. </TreeView.ItemTemplate>  
  16. </TreeView>  
  17. </Grid>  
  18. </Window>