Kotan Code 枯淡コード

In search of simple, elegant code

Menu Close

WP7: Presenting ListBox Items inside a WrapPanel

This morning I was trying to figure out how to display a list of items that ran horizontally across the screen. At first I tried a StackPanel but that didn’t work the way I wanted. After a few minutes of searching I remembered that the WP7 Control Toolkit from Codeplex includes a WrapPanel control. This control does exactly what it says – it lays out the child elements and then wraps them when an element might otherwise be clipped by the edge of the screen or the edge of the parent container.

So then I tried to figure out how I could get this WrapPanel to display items from a data-bound list. This is when I remembered that I wasn’t really thinking in Xaml. I don’t want to bind the child elements of the WrapPanel, what I want to do instead is tell a ListBox that it should use the WrapPanel as a content presenter instead of the default panel that it uses.

The Xaml for this was remarkably simple:

<ListBox x:Name="myList">
<toolkit:WrapPanel ItemHeight="150" ItemWidth="150"/>
<Image Source="103-Person.png" Height="48" Width="48"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextSubtleStyle}"
Width="100" TextAlignment="Center"/>

When you supply this listbox with some data (in my case,  just Person objects with a Name property), it might look something like the screen below. I numbered them when setting the people’s names so you could see how the WrapPanel is laying items out horizontally and then wrapping them down to the next level.

A WrapPanel-based ListBox

A WrapPanel-based ListBox

Changing your ListBox so that it uses a WrapPanel to present items is a simple trick, but it can come in really handy and save you a lot of trouble if you want this wrapped layout style.