First create below class
- public sealed class ItemGroup : NotifyPropertyChanged
- {
- private int _GPID;
- public int GPID
- {
- get { return _GPID; }
- set
- {
- _GPID = value;
- RaiseNotifyPropertyChange("GPID");
- }
- }
- private string _Name;
- public string Name
- {
- get { return _Name; }
- set
- {
- _Name = value;
- RaiseNotifyPropertyChange("Name");
- }
- }
- List<ItemGroup> _chld = new List<ItemGroup>();
- public List<ItemGroup> Chld
- {
- get { return _chld; }
- set
- {
- _chld = value;
- RaiseNotifyPropertyChange("Chld");
- }
- }
- }
Create Observable Collection and initialise in constructor
- public ObservableCollection<ItemGroup> Items { get; set; }
Now, fetch your data in datatable and call below methods
- private void BuildTree(ObservableCollection<ItemGroup> objTreeView)
- {
- if (dt != null)
- {
- foreach (DataRow dataRow in dt.Rows)
- {
- if (Convert.ToInt32(dataRow["GPID"]) == 0)
- {
- var obj = new ItemGroup();
- obj.Name = dataRow["Name"].ToString();
- foreach (ItemGroup childnode in GetChildNode(Convert.ToInt64(dataRow["GID"])))
- {
- obj.Chld.Add(childnode);
- }
- objTreeView.Add(obj);
- }
- }
- }
- }
- private List<ItemGroup> GetChildNode(long parentid)
- {
- List<ItemGroup> childtreenodes = new List<ItemGroup>();
- DataRow[] tmptbl = dt.Select("GPID = " + parentid);
- foreach (DataRow dataRow in tmptbl)
- {
- ItemGroup childNode = new ItemGroup();
- childNode.Name = dataRow["Name"].ToString();
- foreach (ItemGroup cnode in GetChildNode(Convert.ToInt64(dataRow["GID"])))
- {
- childNode.Chld.Add(cnode);
- }
- childtreenodes.Add(childNode);
- }
- return childtreenodes;
- }
Now, create below window
- <Window x:Class="TreeView.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:self="clr-namespace:TreeView"
- Title="MainWindow" Height="350" Width="525">
- <Window.DataContext>
- <self:MainWindowViewModel></self:MainWindowViewModel>
- </Window.DataContext>
- <Grid Margin="10">
- <TreeView Grid.Row="3" Name="trbMenu" ItemsSource="{Binding Items}">
- <TreeView.ItemTemplate>
- <HierarchicalDataTemplate DataType="{x:Type self:ItemGroup}" ItemsSource="{Binding Chld}">
- <TextBlock Text="{Binding Name}" />
- </HierarchicalDataTemplate>
- </TreeView.ItemTemplate>
- </TreeView>
- </Grid>
- </Window>