我知道这是一个老问题,但对我来说仍然很重要。
就我而言,我认为 aTreeView
不会削减它,因为我需要正好两层,并且两层之间显示的项目类型不同。另外,我正在重构一个Expander
s 列表,所以我更加一维地思考。
但是后来我意识到您可以自定义 的ItemTemplate
以TreeView
包含您自己的HierarchicalDataTemplate
,并且您可以使用自己量身定制的ItemTemplate
... Presto!正好两层,每一层都有不同的东西!HierarchicalDataTemplate
DataTemplate
所以我的观点是TreeView
足够灵活,你应该尽量不要创建自己的自定义控件。
这是我所做的:
XAML:
<Page x:Class="Foo.Views.TreePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Foo.Views"
xmlns:viewModel="clr-namespace:Foo.ViewModels"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="Tree page"
d:DataContext="{d:DesignInstance Type=viewModel:TreeModel}">
<TreeView
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.VirtualizationMode="Recycling"
ScrollViewer.CanContentScroll="True"
VirtualizingPanel.ScrollUnit="Pixel"
ItemsSource="{Binding Values}"><!-- IList<Person> -->
<TreeView.ItemTemplate><!-- Template for first layer, which has a HierarchicalDataTemplate so that this layer will expand -->
<HierarchicalDataTemplate
ItemsSource="{Binding Expenses}"><!-- IList<Expense> -->
<HierarchicalDataTemplate.ItemTemplate><!-- Template for the second layer, which has a DataTemplate instead of HierarchicalDataTemplate so that this layer won't expand -->
<DataTemplate>
<TextBlock Text="{Binding Amount}"/><!-- Expense amount in dollars -->
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
<TextBlock Text="{Binding Name}"/><!-- Person name -->
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Page>
Person
班级:
public class Person
{
public string Name { get; set; }
public List<Expense> Expenses { get; set; }
}
Expense
班级:
public class Expense
{
public double Amount { get; set; }
}
这是它的外观:

我用Snoop检查了它以证明它是 UI 虚拟化。TreeViewItem
这是应用较小时的加载次数:

...这TreeViewItem
是应用全屏时加载的 s 数量(它不断超出此代码段,但您明白了):

现在只需简单地设置样式即可使嵌套层看起来像我想要的那样!
编辑:我刚刚验证TreeView
虚拟化了它的所有层,而不仅仅是第一层。