Stackpanel scrollbar visibility issue

It is not new for someone playing around with Silverlight to realize that the ScrollViewer class does not behave as it should when used with a container control like StackPanel.  I spent an hour scratching my head over this issue until finally I got it right ( that is what I think!). All I wanted to do was dynamically add my usercontrols as children to a StackPanel, and the StackPanel needs to display the scrollbars once the child controls go beyond the view of the StackPanel. If you do the following you would not achieve what I said earlier –:

<StackPanel Height="228" x:Name="stackStores" Width="380" Orientation="Vertical" 

ScrollViewer.HorizontalScrollBarVisibility="Auto"

ScrollViewer.VerticalScrollBarVisibility="Auto">

</StackPanel>

The key here is the scrollviewer must move a container as a whole and not its individual children. What I mean is if we add all the usercontrols inside a stackpanel and put this stackpanel inside a scrollviewer, the scrollbars would be visible provided the stackpanel dimensions goes beyond the scrollviewer dimensions. Below is the snippet illustrating the same –:

<StackPanel>

<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Width="500" Height="400">

<StackPanel Height="Auto" x:Name="stackStores" Width="300" Orientation="Vertical"

//Add the children here.

</StackPanel>

</ScrollViewer>

</StackPanel>

The above snippet works for me. I have seen quite a few blogs explaining stuff about this but none had solved my issue.


Happy Programming!

Abhang Rane


12 comments :

Reader's Comments

  1. Thanks for that. I'd spent ages trying to work out the same thing and that worked perfectly.

    ReplyDelete
  2. Thanks a lot, think you can skip the outer stackpanel as well, worked out for me.

    ReplyDelete
  3. Ya thats right, the outer panel was just a container for some of my other stuff.

    ReplyDelete
  4. Actually in Silverlight 3 I was able to just put a stackpanel inside of a scrollviewer and it worked. It doesn't if you put it inside of a list box however.

    ReplyDelete
  5. Havent tried out Silverlight 3 for this yet. Thanks for your input though.

    ReplyDelete
  6. Thank You Very Much Rane (Is Rane the surname?)

    I've seen a lot of curious posts at the web too.
    I've tried it in Silverlight 3.0 and it's THE solution.

    Great Stuff

    regards from Bavaria

    Stefan

    ReplyDelete
  7. Yup reimste, Rane is the surname :).

    ReplyDelete
  8. Thanks it worked perfectly

    ReplyDelete
  9. Thanks, saved me some time here. was trying to find the solution for a bit

    ReplyDelete
  10. Thank you so much! this is helpful. :)

    ReplyDelete