3

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

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
ARZ
  • 2,461
  • 3
  • 34
  • 56

2 Answers2

3

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
ARZ
  • 2,461
  • 3
  • 34
  • 56
  • Could you explain where the convert function is implemented? Do you have a custom converter class which implements IValueConverter or something? – Lorgarn Jul 23 '15 at 09:25
  • And an explenation on the 'MyTable' Object would also be nice. I am sorry, I am not able to reprduce your answer in this state. – Lorgarn Jul 23 '15 at 09:48
  • Yes. I have a custom converter class which implements IValueConverter with first Convert function. The 'MyTable' Object was something like the table that shown in question body with Id and Parent_id columns. – ARZ Jul 28 '15 at 07:13
1

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.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Ralph Shillington
  • 20,718
  • 23
  • 91
  • 154