#400 – Using a WrapPanel as the Items Panel for a ListBox

The ItemsPanel property of a ListBox specifies the template that defines the panel used to contain the elements of the ListBox.  You can override the normal vertically stacked layout of a ListBox by defining your own template.

If you set the ItemsPanel template to contain a WrapPanel, the ListBox will show its child elements left to right, wrapping to the next row when each row fills up.

In the example below, we bind a ListBox to a list of movies, specify an ItemTemplate that dictates how each item appears, and then specify a template for the ItemsPanel that contains a WrapPanel.

    <Grid>
        <ListBox ItemsSource="{Binding MovieList}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <Image Source="{Binding Image}" Stretch="None"/>
                        <Label Content="{Binding TitleWithYear}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel IsItemsHost="True" Orientation="Horizontal"  />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </Grid>

Notice that the layout changes as we resize the parent window.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

6 Responses to #400 – Using a WrapPanel as the Items Panel for a ListBox

  1. Snahc says:

    Hey man nice, i am a beginner and i just learn to do this, but i have a question, if i wanna justify the items, in the right side of the movie list is a blank space, how can i remove it?.

    sorry my english.

  2. Pingback: #1,006 – Scrollbars in a ListBox Appear as Needed | 2,000 Things You Should Know About WPF

  3. Pingback: #1,016 – Displaying a Collection of Items in a WrapPanel | 2,000 Things You Should Know About WPF

  4. Pingback: Windows Phone: WrapPanel | wp7appdevelopment

  5. Pingback: Tooltip For Listbox Items | Ahcjrolen

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: