ListBox 默认是UI虚拟化的。
1. 原生使用
- <ListBox VirtualizingPanel.IsVirtualizing="True"
- VirtualizingPanel.VirtualizationMode="Recycling">
- </ListBox>
为ListBox 设置一个ItemTemplate
- <DataTemplate x:Key="ListBoxDataTemplate">
- <Grid Loaded="Grid_Loaded">
- <Label Content="{Binding Name}"></Label>
- </Grid>
- </DataTemplate>
在 Grid_Loaded 事件中可以看到 实例化的次数
- int index = 0;
- private void Grid_Loaded(object sender, RoutedEventArgs e)
- {
- Console.WriteLine(index);
- index++;
- }
2. 当修改 ListBox 的Template属性时 ,UI虚拟化就失效了
- <Setter Property="Template">
- <Setter.Value>
- <ControlTemplate TargetType="{x:Type ListBox}">
- <ScrollViewer x:Name="ScrollViewer" CanContentScroll="false">
- <ItemsPresenter />
- </ScrollViewer>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
这是标配写法ScrollViewer 中包裹 <ItemsPresenter />
这时ScrollViewer 控件的 CanContentScroll="false"(物理滚动) 要改为 CanContentScroll="true"(逻辑滚动)
ListBox 默认是逻辑滚动,(一项一项滚动)。改变模板时,需要重新设置
附件属性 ScrollViewer.CanContentScroll="True" 这个时候Ui虚拟化重新出现
3.修改Listbox 的ItemsPanel 模板添加一下代码也是可以ui虚拟化(除非你修改了ItemsPanel 模板,因为默认就是虚拟化的。)
- <Setter Property="ItemsPanel">
- <Setter.Value>
- <ItemsPanelTemplate >
- <VirtualizingStackPanel Orientation="Vertical"/>
- </ItemsPanelTemplate>
- </Setter.Value>
- </Setter>
全部代码
- <Window x:Class="VirtualizingStackPanelDemo.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- Title="MainWindow" Height="350" Width="525">
- <Window.Resources>
- <DataTemplate x:Key="ListBoxDataTemplate">
- <Grid Loaded="Grid_Loaded">
- <Label Content="{Binding Name}"></Label>
- </Grid>
- </DataTemplate>
- <Style x:Key="ListBoxStyle" TargetType="{x:Type ListBox}">
- <Setter Property="BorderThickness" Value="0"></Setter>
- <Setter Property="Margin" Value="0 0 5 0"></Setter>
- <Setter Property="MinWidth" Value="150"></Setter>
- <Setter Property="MaxHeight" Value="350"></Setter>
- <Setter Property="Height" Value="350"></Setter>
- <Setter Property="SnapsToDevicePixels" Value="True" />
- <Setter Property="ScrollViewer.CanContentScroll" Value="True"></Setter>
- <Setter Property="Template">
- <Setter.Value>
- <ControlTemplate TargetType="{x:Type ListBox}">
- <ScrollViewer x:Name="ScrollViewer" CanContentScroll="True">
- <ItemsPresenter />
- </ScrollViewer>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- <!--<Setter Property="ItemsPanel">
- <Setter.Value>
- <ItemsPanelTemplate >
- <VirtualizingStackPanel Orientation="Vertical"/>
- </ItemsPanelTemplate>
- </Setter.Value>
- </Setter>-->
- </Style>
- </Window.Resources>
- <Grid>
- <ListBox Style="{StaticResource ListBoxStyle}" ItemTemplate="{StaticResource ListBoxDataTemplate}" x:Name="listbox"></ListBox>
- </Grid>
- </Window>
总结 :
1.Listbox 默认虚拟化
2.修改ListBox Template时 ,重新设置ListBox 附加属性ScrollViewer.CanContentScroll 为"True",以及
<ScrollViewer CanContentScroll="True">
<ItemsPresenter />
</ScrollViewer>