WPF Treeview Using Self Reference Table and Entity Framework
Self reference table and treeview is a common UI scenario where if we want to have N-Level of treeview hierarchy. This article explains how to create a treeview in WPF using a self reference table in SQL Server and using entity framework.
**1. Create Self Reference Table in SQL Server:
**
Create the table in SQL server using the below mentioned script.
CREATE TABLE [dbo].[SelfReferenceNodes](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ParentNodeId] [int] NULL,
[NodeName] [varchar](255) NULL
CONSTRAINT [PK_SelfReferenceNodes] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SelfReferenceNodes] WITH CHECK ADD CONSTRAINT [FK_SelfReferenceNodes] FOREIGN KEY([ParentNodeId])
REFERENCES [dbo].[SelfReferenceNodes] ([Id])
GO
ALTER TABLE [dbo].[SelfReferenceNodes] CHECK CONSTRAINT [FK_SelfReferenceNodes]
GO
Table should have a Primary key Id. It should a column ParentId which will be self referenced to the same table to develop the hierarchy.
**2. Generate Model from Database:
**
Create a ADO.NET entity model from database. It will look as mentioned below.
**3. Create TreeView in WPF.
**
Treeview is constructed using a converter and a HierarchicalDataTemplate. Where the ITemSource of the child nodes are generated dynamically during runtime using the selfreference table.
XAML:
<Grid>
<Grid.Resources>
<local:HierarchyConverter x:Key="HierarchyConverter" />
<HierarchicalDataTemplate x:Key="SelfRefTemplate" ItemsSource="{Binding Converter={StaticResource HierarchyConverter}}">
<TextBlock Text="{Binding NodeName}" />
</HierarchicalDataTemplate>
</Grid.Resources>
<TreeView Name="selfReferenceTree" ItemsSource="{Binding Converter={StaticResource HierarchyConverter}}" ItemTemplate="{StaticResource SelfRefTemplate}" >
</TreeView>
</Grid>
Binding in Code Behind:
TreeEntities treeEntitiesContext = new TreeEntities();
selfReferenceTree.ItemsSource = treeEntitiesContext.SelfReferenceNodes.Where(x => x.ParentNodeId == null).ToList();
Converter:
class HierarchyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var node = value as SelfReferenceNode;
return node.SelfReferenceNodes1.Where(i => i.ParentNodeId == node.Id).ToList();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
4.Sample Data:
Create the sample data in SQL server as mentioned below.
Sample Treeview
Hope it is clear to create a Treeview in WPF using self reference table.
Happy Coding!!!!!
Reference: http://stackoverflow.com/questions/14161963/how-to-bind-self-referencing-table-to-wpf-treeview