如何在 WPF 中动态填充 treeView 从数据库中获取值? [英] How to Dynamically Populate a treeView in WPF getting value from database?
本文介绍了如何在 WPF 中动态填充 treeView 从数据库中获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 WPF 中填充从数据库中获取父节点和节点的树.我的数据库结构是这样的;
I want to populate a tree getting parent and nodes from database in WPF. My database structure is as;
这里的deficitID是节点的id,parentID是父节点的id.
Here deficiencyID is the id of the node and parentID is the id of the parent.
推荐答案
您可以使用这样的实体为您的数据库表建模:
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 ...//
}
然后看看这个答案.
带有树视图的 XAML 可以是这样的:
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
这篇关于如何在 WPF 中动态填充 treeView 从数据库中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文