How to add a ScrollBar to a StackPanel in Silverlight?

programatique picture programatique · Apr 22, 2010 · Viewed 13.6k times · Source

I have a Grid, 3 by 3 (3 RowDefinitions and 3 ColumnDefinitions). I want some content (a StackPanel) in one of those grid cells to scroll. I'm fairly sure this is possible but I cannot figure out how. I've tried adding ScrollViewers and ScrollBar controls to the grid cell I want to scroll, but this usually ends up creating scrolling for the entire page.

Edit: My issue is more specificlly how I can get scrolling over a StackPanel. An example if the issue I am having is here:

<Grid x:Name="LayoutRoot">
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <Grid>
        <TextBlock FontSize="16">1,1</TextBlock>
    </Grid>
    <Grid Grid.Column="1">
        <TextBlock FontSize="16">1,2</TextBlock>
    </Grid>
    <Grid Grid.Row="1">
        <TextBlock FontSize="16">2,1</TextBlock>
    </Grid>
    <Grid Grid.Column="1" Grid.Row="1">
        <StackPanel>
            <TextBlock>Title</TextBlock>
            <Grid>
                <ScrollViewer>
                    <StackPanel>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                        <TextBlock FontSize="32">2,2</TextBlock>
                    </StackPanel>
                </ScrollViewer>
            </Grid>
        </StackPanel>
    </Grid>
</Grid>

Answer

dthorpe picture dthorpe · Apr 22, 2010

StackPanel treats its content has having infinite space. To scroll the stackpanel, you're going to have to put a height constraint on something - the grid parent of the stackpanel, most likely.