如何动态填充WPF中的treeView从数据库中获取值?

时间:2012-11-23 10:20:19

标签: wpf treeview

我想在WPF中填充从数据库获取父节点和节点的树。我的数据库结构是; enter image description here

这里,defectID是节点的id,parentID是父节点的id。

1 个答案:

答案 0 :(得分:0)

您可以使用如下实体为db表建模:

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

然后看看this answer

编辑:你的树视图的XAML可以是这样的:

<!--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>

你的代码隐藏应该是这样的:

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