【问题标题】:How to Dynamically Populate a treeView in WPF getting value from database?如何在 WPF 中动态填充树视图以从数据库中获取值?
【发布时间】:2012-11-23 10:20:18
【问题描述】:

我想在 WPF 中填充从数据库中获取父节点和节点的树。我的数据库结构如下;

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

【问题讨论】:

标签: wpf treeview


【解决方案1】:

您可以使用这样的实体为您的数据库表建模:

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

【讨论】:

  • 米歇尔,我没有完全理解你的意思。您能否以更详尽的形式提供代码。因为我已经有了这个类,但我想知道如何强制 XAML 显示通用树视图。其中也有一些更深的节点。
  • Michele -- 这里的 Items 是指{Binding Path=Items}?这是列表名称还是什么?谢谢
  • ICollectionView 有一个名为 Groups 的属性,您可以通过添加 GroupDescription 来填充该属性。每个组都有两个主要属性:名称(您在 HierarchicalDataTemplate 的第一级绑定)和项目(即分组对象的列表)。所以 Items 是我绑定到 HierarchicalDataTemplate 的 ItemsSource 属性的 Group 的属性。参考这里msdn.microsoft.com/en-us/library/…
  • 谢谢 Michele ,它有效,但有一个小问题。最上根没有显示。但它的孩子和子孩子也在显示。
  • 我们如何显示多个根,现在我的函数使用单个根将通用列表中的根和子项与数据集分开。
猜你喜欢
  • 2013-09-21
  • 2022-01-24
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多