Avrohom Yisroel
Avrohom Yisroel

Reputation: 9440

How to make the items in a WPF ListBox wrap horizontally and vertically

I want to show a list of thumbnails, and allow the user to choose one. A ListBox seemed an obvious choice, setting the template to include the thumbnail and description.

The following code does this correctly...

<ListBox Margin="5"
         Name="BackgroundsLb">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Border Margin="5"
              BorderBrush="Black"
              BorderThickness="1">
        <StackPanel Margin="5">
          <Image Source="{Binding Path=Data, Converter={StaticResource BytesToImageVC}}"
                 Width="150"
                 HorizontalAlignment="Center" />
          <TextBlock Text="{Binding Path=Description}"
                     HorizontalAlignment="Center" />
        </StackPanel>
      </Border>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

However, this displays the thumbnails vertically, one per row, as is normal for a ListBox. Given that the thumbnails are only 150 pixels wide, I would like to show them in something more like a grid, but (ideally) in a way so that the number of columns adapts to the size of the window.

I tried replacing the ListBox with an ItemsControl, adding in the following...

  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <WrapPanel Orientation="Vertical" />
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>

...and it displayed exactly how I wanted it, but the ItemsControl does not allow selection, so is no use for my purpose.

Is there a way to achieve a flexible, selectable display that fills the horizontal space, and breaks onto a new row according to the size of the window?

Thanks

Upvotes: 0

Views: 1120

Answers (1)

Jason Tyler
Jason Tyler

Reputation: 1389

You can use an ItemsPanelTemplate in a ListBox just the same as you are using one in the ItemsControl. The difference I think you're seeing is that ListBox uses scroll bars by default rather than wrapping the content. Basically the content is allowed to grow forever, so you never get the wrap. Instead you get a scrollbar. The good news is you can disable this behavior. The following should give you a horizontal wrap, where new rows are created as needed.

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal" />
         </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

Upvotes: 3

Related Questions