ItemsControl、VirtualizingStackPanel 和 ScrollViewer 高度
我想使用 ItemsControl 显示重要的项目列表。
我使用 ItemsControl 的原因是 DataTemplate 在我正在处理的应用程序中要复杂得多:提供的示例代码仅反映了我遇到的大小调整问题。
我希望:
- ItemsControl 被虚拟化,因为有很多项目要显示
其大小自动扩展到其父容器(网格)
<前><代码><网格><控制模板> <堆栈面板> <堆栈面板> <数据模板>
背后的代码是:
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 周围放置一个滚动查看器可以提供预期的视觉结果,但虚拟化消失并且列表需要太多时间来显示。
如何实现 ItemsControl 的自动高度扩展和虚拟化?
I want to display a important list of items using an ItemsControl.
The reason why I'm using an ItemsControl is that the DataTemplate is much more complex in the application I'm working on: The sample code provided only reflects the sizing problem I have.
I would like :
- 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>
The code behind is :
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;
}
}
As I force the ScrollViewer height to 400px, ItemsControl virtualization works as I expect: The ItemsControl displays the list very quickly, regardless of how many items it contains.
However, if I remove Height="400px", the list will expand its height to display the whole list, regardless its parent container height. Worse: it appears behind its container.
Putting a scrollviewer around the ItemsControl gives the expected visual result, but the virtualization goes away and the list takes too much time to display.
How can I achieve both automatic height expansion and virtualization of my ItemsControl ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在 ItemsControl.Template 中:您在那里使用 StackPanel,这为她的孩子提供了他们想要的高度。将其替换为类似的内容
并且它应该可以正常工作。
希望有帮助。
The problem is in the ItemsControl.Template: you use StackPanel there, which gives her children as much height as they want. Replace it to something like
And it should work fine.
Hope it helps.