views:

1299

answers:

1

Hi,

I'm using a WrapPanel to format some text. During runtime I add TextBlocks and StackPanels as Children. Obviously I need a scrollbar depending on the data size. Searching the web I found multiple answers which all propose to put a ScrollViewer around the WrapPanel. That makes sense to me, but I cannot get it to work. Here's my code:

scrollView = new ScrollViewer();
scrollView.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
scrollView.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
scrollView.HorizontalAlignment = HorizontalAlignment.Stretch;
scrollView.VerticalAlignment = VerticalAlignment.Stretch;
scrollView.Margin = new Thickness(0);
scrollView.BorderThickness = new Thickness(0);  

textPanel = new WrapPanel();
textPanel.Width = Width;
scrollView.Content = textPanel;

That does not work. The ScrollViewer seems to grow with the contained WrapPanel. If I set the vertical scroll bar to visible, I can see that the scrollbar grows with the content. But the ScrollViewer grows out of the containing window and therefor no scrollbar is displayed ever.

Any hint what I might be doing wrong?

cheers, Achim

+2  A: 

You need something to contrain the size of the WrapPanel and the ScrollViewer - you could set the width and height of the viewer then use an element binding on the wrappanel:

 <ScrollViewer x:Name="ScrollViewer1" 
Width="200" 
Height="200"  
ScrollViewer.VerticalScrollBarVisibility="Visible"
  ScrollViewer.HorizontalScrollBarVisibility="Visible" >
                <controls:WrapPanel 
                      Width="{Binding ElementName=ScrollViewer1, Path=Width}" 
                      Height="{Binding ElementName=ScrollViewer1, Path=Height}">

Hope that helps.

Ian

Ian Blackburn
Yes, that was probably the problem. I moved the ScrollViewer into a Grid - which seems to restrict the size - and everything worked fined. Thanks for your answer!
Achim