我希望使用ItemsControl来展示一组重要的项目。
我选择使用ItemsControl的原因是,在我所工作的应用中,DataTemplate要复杂得多:提供的示例代码只反映了我遇到的大小问题。
我希望:
- the ItemsControl to be virtualized because there is many items to display
its size to expand to its parent container automatically (the Grid)
<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高度强制设置为400px时,ItemsControl的虚拟化按照我的预期工作:无论它包含多少项,ItemsControl都会非常快速地显示列表。
然而,如果我删除Height =“400px”,则该列表将展开其高度以显示整个列表,而不考虑其父容器的高度。更糟糕的是:它出现在其容器的后面。
在ItemsControl周围放置一个ScrollViewer可以得到预期的视觉效果,但是虚拟化会消失,列表需要太长时间才能显示。
如何实现自动高度扩展和ItemsControl的虚拟化?