0

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

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

1 Comment

That's completely brilliant, thanks. I'd tried using a WrapPanel, but without disabling the horizontal scrollbar, it didn't help. That extra trick did the job. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.