ARZ
ARZ

Reputation: 2491

How to bind Self-referencing table to WPF TreeView

What is the best solution to bind a self-referncing table from edmx like:

enter image description here

to a WPF TreeView control to have something like:

enter image description here

Upvotes: 3

Views: 4284

Answers (2)

ARZ
ARZ

Reputation: 2491

I solve the problem using this Binding Converter:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var item = value as MyTable;
        return  item.MyTable1.Where(i => i.parent_id== item.id); //return children
    }

.xaml :

<TreeView Name="treeview1" ItemsSource="{Binding Converter={StaticResource HierarchyConverter}}" ItemTemplate="{StaticResource ItemTemplate}" >
      <TreeView.Resources>
            <local:HierarchyConverter x:Key="HierarchyConverter" />
            <HierarchicalDataTemplate x:Key="ItemTemplate" ItemsSource="{Binding Converter={StaticResource HierarchyConverter}}">
                  <TextBlock Text="{Binding element_name}" />
            </HierarchicalDataTemplate>
      </TreeView.Resources>
</TreeView>

.cs :

treeview1.ItemsSource = db.MyTable.Where(x => x.partnt_id== null);//elements that have no parent

Upvotes: 3

Ralph Shillington
Ralph Shillington

Reputation: 21098

Josh Smith has an excellent article on Code Project that walks you through how to craft a view model that your TreeView can bind to. You'll not get away with just using the EF because EF doesn't do recursion.

Upvotes: 1

Related Questions