XAML Horizontal Stackpanel Scrolling

Riot9 picture Riot9 · Oct 10, 2013 · Viewed 7.6k times · Source

I am having problems getting horizontal stackpanels to scroll from within a scrollviewer. What I'm trying to do is more complex than my example, but after removing variables I think I can figure everything out if I can solve this last problem.

Basically, I can't get a scrollviewer to scroll horizontally when it contains a horizontal stackpanel.

Here is the sample XAML:

   <ScrollViewer>
        <StackPanel Orientation="Horizontal">
            <Image Source="test.png" Width="400" Height="400"/>
            <Image Source="test.png" Width="400" Height="400"/>
            <Image Source="test.png" Width="400" Height="400"/>
            <Image Source="test.png" Width="400" Height="400"/>
            <Image Source="test.png" Width="400" Height="400"/>
            <Image Source="test.png" Width="400" Height="400"/>
            <Image Source="test.png" Width="400" Height="400"/>
        </StackPanel>
    </ScrollViewer>

Strangely, if I just swap the orientation from Horizontal to Vertical, it scrolls just fine. I've read on multiple posts that stackpanels have issues that can make them a poor fit for scrollviewers, so I tried it with a grid as well, but get the same results.

  <ScrollViewer>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="400"/>
                <ColumnDefinition Width="400"/>
                <ColumnDefinition Width="400"/>
                <ColumnDefinition Width="400"/>
                <ColumnDefinition Width="400"/>
                <ColumnDefinition Width="400"/>
            </Grid.ColumnDefinitions>                
            <Image Source="test.png" Width="400" Height="400"  Grid.Column="0"/>
            <Image Source="test.png" Width="400" Height="400"  Grid.Column="1"/>
            <Image Source="test.png" Width="400" Height="400"  Grid.Column="2"/>
            <Image Source="test.png" Width="400" Height="400"  Grid.Column="3"/>
            <Image Source="test.png" Width="400" Height="400"  Grid.Column="4"/>
            <Image Source="test.png" Width="400" Height="400"  Grid.Column="5"/>
        </Grid>
    </ScrollViewer>

It seems so simple that I feel like I'm misunderstanding something fundamental. If anyone can help out, I'd be extremely grateful.

Answer

McGarnagle picture McGarnagle · Oct 10, 2013

You just have to turn on horizontal scrolling. It's hidden by default (but the vertical one is not, hence the confusion).

<ScrollViewer HorizontalScrollBarVisibility="Auto">