I want to populate a tree getting parent and nodes from database in WPF. My database structure is as;
Here deficiencyID is the id of the node and parentID is the id of the parent.
I want to populate a tree getting parent and nodes from database in WPF. My database structure is as;
Here deficiencyID is the id of the node and parentID is the id of the parent.
You can model your db table with an entity like this:
public class Deficiency
{
public int DeficiencyID { get; set; }
public int ParentID { get; set; }
//... OTHER PROPERTIES ...//
}
then take a look at this answer.
EDIT: Your XAML with the treeview can be like this:
<!--Bind to Groups generated from codebehind
Every group have property Name and Items -->
<TreeView Name="treeview1" ItemsSource="{Binding Groups}" >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Items}">
<!-- Here Bind to the name of the group => this is the Parent ID -->
<TextBlock Text="{Binding Path=Name}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<StackPanel>
<!-- Here the data context is your class Deficiency,
so bind to its properties-->
<TextBlock Text="{Binding Path=DeficiencyID}"/>
<!-- ... -->
<TextBlock Text="{Binding Path=OtherProperties}"/>
<!-- ... -->
</StackPanel>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
and your codebehind should be something like this:
List<Deficiency> myList = new List<Deficiency>();
// here load from DB //
ICollectionView view = CollectionViewSource.GetDefaultView(myList);
view.GroupDescriptions.Add(new PropertyGroupDescription("ParentID"));
treeview1.DataContext = view;
HTH