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.

有帮助吗?

解决方案 3

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.

其他提示

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.

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.

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top