Lar*_*rry 9 wpf itemscontrol scrollviewer virtualizingstackpanel
我想使用ItemsControl显示重要的项目列表.
我正在使用ItemsControl的原因是DataTemplate在我正在处理的应用程序中要复杂得多:提供的示例代码仅反映了我的调整问题.
我想要 :
它的大小自动扩展到其父容器(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>
Run Code Online (Sandbox Code Playgroud)
背后的代码是:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我强制ScrollViewer高度为400px时,ItemsControl虚拟化按预期工作:ItemsControl非常快速地显示列表,无论它包含多少项.
但是,如果我删除Height ="400px",列表将扩展其高度以显示整个列表,无论其父容器高度如何.更糟糕的是:它出现在它的容器后面.
在ItemsControl周围放置一个scrollviewer可以得到预期的可视化结果,但虚拟化消失了,列表需要花费太多时间来显示.
如何实现ItemsControl的自动高度扩展和虚拟化?
问题在于ItemsControl.Template:你在那里使用StackPanel,这给了她的孩子尽可能多的高度.把它换成类似的东西
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel>
<TextBlock Text="this is a title" FontSize="15" />
<TextBlock Text="This is a description" />
</StackPanel>
<ScrollViewer CanContentScroll="True" Grid.Row="1">
<VirtualizingStackPanel />
</ScrollViewer>
</Grid>
Run Code Online (Sandbox Code Playgroud)
它应该工作正常.
希望能帮助到你.