我想使用 ItemsControl 显示重要的项目列表。
我使用 ItemsControl 的原因是 DataTemplate 在我正在处理的应用程序中要复杂得多:提供的示例代码仅反映了我遇到的大小问题。
我想 :
- 要虚拟化的 ItemsControl,因为要显示的项目很多
它的大小自动扩展到其父容器(网格)
<Grid> <ItemsControl x:Name="My" ItemsSource="{Binding Path=Names}"> <ItemsControl.Template> <ControlTemplate> <StackPanel> <StackPanel> <TextBlock Text="this is a title" FontSize="15" /> <TextBlock Text="This is a description" /> </StackPanel> <ScrollViewer CanContentScroll="True" Height="400px"> <VirtualizingStackPanel IsItemsHost="True" /> </ScrollViewer> </StackPanel> </ControlTemplate> </ItemsControl.Template> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid>
后面的代码是:
public partial class Page1: Page
{
public List<string> Names { get; set; }
public Page1()
{
InitializeComponent();
Names = new List<string>();
for(int i = 0; i < 10000; i++)
Names.Add("Name : " + i);
My.DataContext = this;
}
}
当我将 ScrollViewer 的高度强制为 400 像素时,ItemsControl 虚拟化按我的预期工作:ItemsControl 非常快速地显示列表,无论它包含多少项目。
但是,如果我删除 Height="400px",列表将扩展其高度以显示整个列表,而不管其父容器高度。更糟糕的是:它出现在它的容器后面。
在 ItemsControl 周围放置一个滚动查看器可以提供预期的视觉效果,但是虚拟化消失了,并且列表需要花费太多时间来显示。
如何实现 ItemsControl 的自动高度扩展和虚拟化?