I have a tree view of items, which currently shows all the levels of children, down to the furthest. How can I achieve to show only the first level of children? Is the HierarchicalDataTemplate
the wrong approach, perhaps? Collapsing the children of level 2 and further would not be sufficent.

- 17,971
- 7
- 53
- 66

- 3,584
- 4
- 23
- 53
4 Answers
How about using a filtered version of your datasource so only the levels you want are included, then you can use a HierarchialDataTemplate without any problem.

- 4,126
- 2
- 25
- 40
-
My datasource is a collection of a class like this: `public MyClass { public List
Children { get; set; } }`. I could only filter it through manipulating the data itself or shadow copying the data till the first level of children. That would make the actual data manipulation more complicated, though. How about another solution? – Michael Schnerring Feb 06 '13 at 16:42
Just use a DataTemplate
, instead of the HierarchicalDataTemplate
.
Edit: Got it. There's a number of options. Tommy's recommendation above is a good one and elegant. Another option is to override the TreeViewItem's ControlTemplate for any item whose children you don't want to see and hide the expander area.

- 17,971
- 7
- 53
- 66
-
Sorry, if I didn't explain my issue well enough. With a `DataTemplate` I'd have a flat list then. I'd like to have the first level of children of each node, though. – Michael Schnerring Feb 06 '13 at 13:20
Well, without manipulating the data it's not possible to just show one level of children. The control would have needed a property, which is able to determine the deepness of shown nodes.
This solution came to me and was quite obvious: I just use two flat tree views, the second one dependent on the SelectedItem
of the first one. No HierarchicalDataTemplate
needed, at all. Just a common DataTemplate
.

- 3,584
- 4
- 23
- 53
As I understand it, you want the top level nodes, and 1 level of children of those, and no further (so there will be 2 levels of nodes overall). Then you can do it with 2 templates if you want to do it in XAML:
<Grid>
<Grid.Resources>
<DataTemplate x:Key="TemplateLeaf">
<TextBlock Text="{Binding Text}" /> <!-- Whatever leaf view you want -->
</DataTemplate>
<sdk:HierarchicalDataTemplate ItemsSource="{Binding Items}" ItemTemplate="{StaticResource TemplateLeaf}" x:Key="TemplateNode">
<TextBlock Text="{Binding Text}" />
</sdk:HierarchicalDataTemplate>
</Grid.Resources>
<sdk:TreeView ItemsSource="{Binding Items}" ItemTemplate="{StaticResource TemplateNode}" />
</Grid>
(That's the Silverlight version but it's the same). By default the HierarchicalDataTemplate
uses itself as its own ItemTemplate
, but you can replace that with some other template for the next level (including a plain DataTemplate
) if you want.

- 2,231
- 1
- 14
- 15