Skip to content

Instantly share code, notes, and snippets.

@PiN73
Last active March 26, 2024 16:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PiN73/1559e6c940dae092a722e71746b87160 to your computer and use it in GitHub Desktop.
Save PiN73/1559e6c940dae092a722e71746b87160 to your computer and use it in GitHub Desktop.
WPF ScrollViewer virtualization AND smooth scroll. Full: https://github.com/PiN73/TestScrollVirtualization/

By default, <ItemsControl>/<ScrollViewer> doesn't use virtualization. All its items are rendered at once. This causes lags/freezing on first render and each re-render (for example, if list data or window size changes).

Adding ScrollViewer.CanContentScroll="True" will enable virtualization and make loading fast. But the list will be scrolled one whole item a time, which feels like jumping if items height is big enough.

To make virtualization enabled and keep smooth scrolling, add also VirtualizingPanel.ScrollUnit="Pixel"

InitializeComponent();
MyButton.Click += (s, e) =>
{
MyButton.Visibility = Visibility.Collapsed;
MyItemsControl.ItemsSource = Enumerable
.Range(0, 10000)
.Select(i => $"Item {i}")
.ToArray();
};
<Grid>
<ItemsControl Name="MyItemsControl"
ScrollViewer.CanContentScroll="True"
VirtualizingPanel.ScrollUnit="Pixel"
VirtualizingStackPanel.VirtualizationMode="Recycling">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer>
<ItemsPresenter/>
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock FontSize="64" Text="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Name="MyButton">Show List</Button>
</Grid>
@pozyx
Copy link

pozyx commented Jul 19, 2022

You have saved my day with this! Thanks

@CodingOctocat
Copy link

With my ListBox, if I want to enable virtualization, I have to set Template, but if I want smooth scrolling, I have to go back to the ListBox to set it, which is weird.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment