- 1 year ago
Several TreeViewItem in one DataTemplate
You can use a HierarchicalDataTemplate
to define a template for a TreeView that includes multiple TreeViewItems. The HierarchicalDataTemplate
allows you to define a template for a tree node that contains child nodes.
Here's an example of how to define a HierarchicalDataTemplate
that includes multiple TreeViewItems:
php<TreeView ItemsSource="{Binding MyItems}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding MyChildItems}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding MyImage}" />
<TextBlock Text="{Binding MyText}" />
</StackPanel>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TreeViewItem Header="{Binding MyChildText}" />
<TreeViewItem Header="{Binding MyOtherChildText}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
In this example, the TreeView
is bound to a collection called MyItems
. The HierarchicalDataTemplate
is used to define the template for each item in the tree.
The HierarchicalDataTemplate
includes a StackPanel
with an Image
and TextBlock
that represents the parent node. The ItemsSource
property is set to MyChildItems
, which is a collection of child items for the parent node.
The HierarchicalDataTemplate
also includes a DataTemplate
that defines the template for child nodes. In this case, the template includes two TreeViewItem
controls that represent child items.
Note that the ItemsSource
property is set to MyChildItems
for the HierarchicalDataTemplate
, and not for the DataTemplate
. This is because the HierarchicalDataTemplate
defines the template for the parent node, while the DataTemplate
defines the template for child nodes.