覆盖 ScrollViewer 的默认控件模板时,VirtualizingStackPanel 停止工作是因为 ScrollViewer 的默认模板中使用了 VirtualizingStackPanel,而覆盖默认模板时,需要手动添加 VirtualizingStackPanel。以下是解决方案:
- 在 ScrollViewer 的样式中添加 VirtualizingStackPanel: <Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ScrollViewer}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<VirtualizingStackPanel Grid.Column="0" Grid.Row="0">
<ContentPresenter Content="{TemplateBinding Content}" />
</VirtualizingStackPanel>
<ScrollBar Name="PART_VerticalScrollBar"
Grid.Column="1" Grid.Row="0"
Value="{Binding Path=VerticalOffset, RelativeSource={RelativeSource TemplatedParent}}"
Maximum="{Binding Path=ExtentHeight, RelativeSource={RelativeSource TemplatedParent}}"
ViewportSize="{Binding Path=ViewportHeight, RelativeSource={RelativeSource TemplatedParent}}"
Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"/>
<ScrollBar Name="PART_HorizontalScrollBar"
Grid.Column="0" Grid.Row="1"
Value="{Binding Path=HorizontalOffset, RelativeSource={RelativeSource TemplatedParent}}"
Maximum="{Binding Path=ExtentWidth, RelativeSource={RelativeSource TemplatedParent}}"
ViewportSize="{Binding Path=ViewportWidth, RelativeSource={RelativeSource TemplatedParent}}"
Orientation="Horizontal"
Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style> <VirtualizingStackPanel IsVirtualizing="True">
<!-- 在此处添加需要虚拟化的内容 -->
</VirtualizingStackPanel>
</ScrollViewer>这样,在覆盖 ScrollViewer 的默认控件模板时,VirtualizingStackPanel 仍然可以正常工作。
- 在需要使用 VirtualizingStackPanel 的 ScrollViewer 中添加 VirtualizingStackPanel.IsVirtualizing="True" 属性: