How to Dynamically Populate a treeView in WPF gett

2019-08-17 23:06发布

I want to populate a tree getting parent and nodes from database in WPF. My database structure is as; enter image description here

Here deficiencyID is the id of the node and parentID is the id of the parent.

标签: wpf treeview
1条回答
仙女界的扛把子
2楼-- · 2019-08-18 00:03

You can model your db table with an entity like this:

public class Deficiency
{
    public int DeficiencyID { get; set; }
    public int ParentID { get; set; }
    //... OTHER PROPERTIES ...//
}

then take a look at this answer.

EDIT: Your XAML with the treeview can be like this:

<!--Bind to Groups generated from codebehind 
    Every group have property Name and Items -->
<TreeView Name="treeview1" ItemsSource="{Binding Groups}" >
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Path=Items}">
            <!-- Here Bind to the name of the group => this is the Parent ID -->
            <TextBlock Text="{Binding Path=Name}" />
            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                    <!-- Here the data context is your class Deficiency, 
                         so bind to its properties-->
                        <TextBlock Text="{Binding Path=DeficiencyID}"/>
                        <!-- ... -->
                        <TextBlock Text="{Binding Path=OtherProperties}"/>
                        <!-- ... -->
                    </StackPanel>
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

and your codebehind should be something like this:

List<Deficiency> myList = new List<Deficiency>();
// here load from DB //       
ICollectionView view = CollectionViewSource.GetDefaultView(myList);
view.GroupDescriptions.Add(new PropertyGroupDescription("ParentID"));
treeview1.DataContext = view;

HTH

查看更多
登录 后发表回答