How to bind a binding table to WPF TreeView

What is the best solution for binding self-referncing tables from edmx, for example:

enter image description here

into a WPF control TreeViewto have something like:

enter image description here

+3
source share
3 answers

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
+3
source

Josh Smith has an excellent article in the Code Project article that talks about how to create a presentation model that yours can bind to TreeView. You will not be able to simply use EF because EF does not perform recursion.

+1
source

ItemsSource .cs xaml . ?! : <local:HierarchyConverter x:Key="HierarchyConverter"/>

Pls, :))

-1

Source: https://habr.com/ru/post/1775578/


All Articles