DEV Community

Cover image for Why a WPF ScrollViewer Does Not Scroll and How to Fix It
s-iguchi09
s-iguchi09

Posted on Edited on Originally published at s-iguchi09.github.io AI-assisted

Why a WPF ScrollViewer Does Not Scroll and How to Fix It

You put a ScrollViewer with VerticalScrollBarVisibility="Auto" under a header in a vertical StackPanel, fill it with items, and no scrollbar ever shows up. The list just runs off the bottom of the window.

This is a short summary. The full article, with the measured heights for each parent layout on .NET 10, is here:
Why a WPF ScrollViewer Does Not Scroll and How to Fix It

The parent is the problem

A vertical StackPanel measures its children with unlimited height. The ScrollViewer therefore asks for the full height of its content and never overflows. In the measurement, 800 px of rows inside a 200 px StackPanel gave a viewport of 800 and a ScrollableHeight of 0.

The fix

Give the ScrollViewer a finite height. A star row of a Grid is the usual way:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <TextBlock Text="Header" />
    <ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
        <!-- items -->
    </ScrollViewer>
</Grid>
Enter fullscreen mode Exit fullscreen mode

A DockPanel with the ScrollViewer as its last child works too, and so does an explicit Height or MaxHeight.

The same cause breaks ListBox virtualization

A 2,000-item ListBox placed inside an outer ScrollViewer or a StackPanel realized all 2,000 containers, because it was given room for every item. Give the ListBox itself a constrained height instead of wrapping it.

A Japanese version is also available.

Related Articles

Top comments (0)