How can I get ScrollViewer to work inside a StackPanel? How can I get ScrollViewer to work inside a StackPanel? wpf wpf

How can I get ScrollViewer to work inside a StackPanel?


This was bugging me for a while too, the trick is to put your stackpanel within a scrollviewer.

Also, you need to ensure that you set the CanContentScroll property of the scroll viewer to True, here's an example:

  <ScrollViewer Grid.Row="1" Margin="299,12,34,54" Name="ScrollViewer1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Height="195" CanContentScroll="True">        <StackPanel Name="StackPanel1" OverridesDefaultStyle="False"  Height="193" Width="376" VerticalAlignment="Top" HorizontalAlignment="Left"></StackPanel>  </ScrollViewer>


You can't without fixing the height of the StackPanel. It's designed to grow indefinitely in one direction. I'd advise using a different Panel. Why do you "need" to have an outer StackPanel?


Notice that sometimes you might have a StackPanel without realizing it. In my case I had this code

<ScrollViewer>  <ItemsControl ItemsSource="{Binding Pages}"/></ScrollViewer>

which worked fine. The "Pages" referenced by the binding was really different, complex UserControls, and I wanted to have only scrollbars on some of them. So I removed the scrollviewer:

 <ItemsControl ItemsSource="{Binding Pages}"/>

And then I put the ScrollViewer as the top element on those of the usercontrols where I wanted them. However, this did not work. The content just flowed off the page. At first i didn't think this question/answer could help me, but the I realized that the default ItemPanel of an ItemsControl is the StackPanel. So I solved my problem by specifying an ItemsPanel that was not the StackPanel:

<ItemsControl ItemsSource="{Binding Pages}">    <ItemsControl.ItemsPanel>        <ItemsPanelTemplate>            <Grid/>        </ItemsPanelTemplate>    </ItemsControl.ItemsPanel></ItemsControl>