开发者

TreeView binding

I have a database table that has Id, Group, Items as columns. How do i code the xaml template with b开发者_如何学编程inding so that the list appears as

Group 1

  • item 1
  • item 2

Group 2

  • item 3


Since you need a hierarchy the best approach in my mind would be a 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.

For items that do not have child items (the "item" items in your example) you can add a regular DataTemplate.

In summary the treeview XAML could look something like this:

        <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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜