在需要使用ListBox加载大量数据时,可以考虑开启虚拟化,但需要注意的是,虚拟化不一定能开启成功。
以下是一些原因:
- ListBox内部的ScorllViewer不能去掉
如果使用了DataTemplate,需要将其中的ItemsPresenter
用ScrollViewer
包裹起来;
<ControlTemplate TargetType="ListBox">
<Border SnapsToDevicePixels="True">
<ScrollViewer CanContentScroll="True">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
</ScrollViewer>
</Border>
</ControlTemplate>
ListBox外面不能使用 ScrollViewer
ListBox的
ScrollViewer.CanContentScroll ="True"
WPF ListBox 像素滚动 (opens new window)
放ListBox的容器必须是有限高度的,不能是StackPanel这样,否则ScrollViewer是不会出现哒。
以下是其它的一些参考文章:
获取视觉树中的元素:
ListboxElementName.GetFirstVisualChild<ScrollViewer>();
Accessing the ScrollViewer of a ListBox from C# (opens new window)