在 WPF 中,利用 ScrollViewer 包裹 Content 后,当 Content 实际的高度/宽度大于设置的高度/宽度时,将会自动出现 ScrollBar,方便用户利用滚动条来查看更多的内容。所以 ItemsControl 簇(继承自 ItemsControl 的一系列控件,如 ListBox,ListView,DataGrid 等)都包含 ScrollViewer。WPF 为 ScrollViewer 提供两种滚动的方式:按物理单元滚动以及按逻辑单元滚动,非此即彼。而两种方式各有千秋:
按物理单元滚动 (ScrollViewer.CanContentScroll = false)
优点:所谓的物理单元,通俗点说就是像素。由于是按照像素进行滚动,所以在此模式下滚动会显的非常平滑。
缺点:也正是由于按照像素进行滚动,所以 ScrollViewer 需要确切地知道它包裹的 Content 的高度、宽度等具体数值。对 ItemesControl 簇来说,也就是要知道每一个 Item 的高度、宽度等数值,即每一个 Item 都会经历 Measure 和 Arrange 阶段,而这两个阶段都是在 UI 线程上进行的,所以当在 ScrollViewer 中的 Item 比较多时,就会导致 UI 变得很卡。
适用:Item 数量比较少的情况。
按逻辑单元滚动 (ScrollViewer.CanContentScroll = true)
优点:
1. 性能比较高,因为它只需要 Measure 和 Arrange 可见的 Item 而非所有的 Item。
2. 滚动的行为比较简单,只需要从一个 Item 滚动到另一个 Item,简单点说就是 index + 1 就可以了,该行为和每个 Item 实际高度没有关系。
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<ScrollViewer HorizontalScrollBarVisibility="Auto">
<StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
<TextBlock TextWrapping="Wrap" Margin="0,0,0,20">Scrolling is enabled when it is necessary.
Resize the window, making it larger and smaller.</TextBlock>
<Rectangle Fill="Red" Width="1000" Height="1000"></Rectangle>
</StackPanel>
</ScrollViewer>
</Window>