简体   繁体   English

TreeView绑定

[英]TreeView binding

I have a database table that has Id, Group, Items as columns. 我有一个具有Id,Group,Items作为列的数据库表。 How do i code the xaml template with binding so that the list appears as 我如何编码具有绑定的xaml模板,以便列表显示为

Group 1 第一组

  • item 1 项目1
  • item 2 项目2

Group 2 2组

  • item 3 项目3

Since you need a hierarchy the best approach in my mind would be a TreeView . 由于您需要层次结构,因此我认为最好的方法是TreeView You have to group the data in the hierarchy you want beforehand, then you can data bind the treeview to the top level items in your data source, in your case the "Group" items. 您必须预先将数据分组到所需的层次结构中,然后才能将树视图数据绑定到数据源中的顶级项目,在本例中为“分组”项目。

For items that do have child items as well you need to add a HierarchicalDataTemplate to the treeview - important here is that whatever object you draw your items from must support a property that contains the collection of child items, this is configured in the ItemsSource attribute. 对于确实具有子项的项,您需要向树视图添加HierarchicalDataTemplate重要的是,从中绘制项的任何对象都必须支持包含子项集合的属性,该属性在ItemsSource属性中配置。

For items that do not have child items (the "item" items in your example) you can add a regular DataTemplate . 对于没有子项的项目(示例中的“ item”项),您可以添加常规DataTemplate

In summary the treeview XAML could look something like this: 总而言之,treeview XAML可能看起来像这样:

        <TreeView Name="myTreeView" ItemsSource="{Binding}" >
            <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type GroupType}" ItemsSource="{Binding Items}">
                </HierarchicalDataTemplate>
                <DataTemplate DataType="{x:Type ItemType}">
                </DataTemplate>
            </TreeView.Resources>
        </TreeView>

To assign the top level nodes once you have created the corresponding data objects (that in turn each have a collection of children assigned) you can simply say: 创建了相应的数据对象(每个数据对象又分配了一组子对象)后,要分配顶级节点,您可以简单地说:

    foreach(GroupType myGroup in myGroupCollection)
        myTreeView.Items.Add(myGroup);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM