How to bind Self-referencing table to WPF TreeView

2019-07-13 11:02发布

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

2条回答
Summer. ? 凉城
2楼-- · 2019-07-13 11:46

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
查看更多
可以哭但决不认输i
3楼-- · 2019-07-13 11:46

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.

查看更多
登录 后发表回答