Silverlight Tip: ScrollViewer for a WrapPanel
The Silverlight wrap panel is a great control which automatically wraps the elements in it either horizontally or vertically as required to fit them within the size of the panel.
Using a wrap panel is fairly simple and straight forward.
<ControlsToolkit:WrapPanel Orientation="Horizontal">
<TextBlock Text="Item 1"/>
<TextBlock Text="Item 2"/>
<TextBlock Text="Item 3"/>
<TextBlock Text="Item 4"/>
<TextBlock Text="Item 5"/>
<TextBlock Text="Item 6"/>
<TextBlock Text="Item 7"/>
<TextBlock Text="Item 8"/>
<TextBlock Text="Item 9"/>
<TextBlock Text="Item 10"/>
</ControlsToolkit:WrapPanel>
The
Orientation can be either
Horizontal or
Vertical.
However, when the number of items are more and the space is limited, wrap panel will not provide scrollbars. Instead, it’ll cut-off the content.
Ok, we have scrollviewer for that purpose. Just put the wrap panel inside a scrollviewer.
Let’s try that.
<ScrollViewer>
<ControlsToolkit:WrapPanel Orientation="Horizontal">
<TextBlock Text="Item 1"/>
<TextBlock Text="Item 2"/>
<TextBlock Text="Item 3"/>
<TextBlock Text="Item 4"/>
<TextBlock Text="Item 5"/>
<TextBlock Text="Item 6"/>
<TextBlock Text="Item 7"/>
<TextBlock Text="Item 8"/>
<TextBlock Text="Item 9"/>
<TextBlock Text="Item 10"/>
</ControlsToolkit:WrapPanel>
</ScrollViewer>
So now I have added a scrollviewer. Let’s see how it’ll look.
Fine, there is a scrollviewer, but instead of using the scrollviewer the wrap panel adjusted all the content with in the panel by reducing the whitespace in between. This is because the
Orientation is set to
Horizontal.
What happens if we change the
Orientation to
Vertical.
Now there is a scrollbar, but what happened to the
Wrapping?
When the
Orientation is set to
Vertical, the wrap panel will first align the content vertically and when the space is not available then it wraps the content to another column. Since we have a scrollviewer here, the vertical space is unlimited, hence all the content in a single row.
That’s a nice explanation. But what is the solution?
For wrap panel to work with in a scrollviewer, you need to take care of the
Width and
ItemWidth properties of wrap panel.
<ControlsToolkit:WrapPanel Orientation="Horizontal"
ItemWidth="200"
Width="Auto">
And here is the result with scrollbar and the content wrapped.
The same trick works when the wrap panel is used in a ItemsControl with
DataBinding. You can either keep your ItemsControl inside a scrollviewer or can change the control template of ItemsControl by adding a scrollviewer to the content presenter inside the template.