Ben Clarke
Ben Clarke

Reputation: 1061

Possible to display images in a ListBox with multiple rows

I am trying to get images in a Listbox to display in a certain way.

Listbox now:

enter image description here

How i want:

enter image description here

As you can see i want the scroll bar to be down the side and there to be multiple columns and rows depending on the size of the listbox.

Upvotes: 0

Views: 180

Answers (2)

Kylo Ren
Kylo Ren

Reputation: 8813

use WrapPanel with Width set to a value. for an example run below code:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525" >
<Window.DataContext>
    <local:ParentViewModel />
</Window.DataContext>

<ListBox  Height="auto" ItemsSource="{Binding MyList,Mode=TwoWay}">
    <ListBox.Style>
        <Style TargetType="{x:Type ListBox}">
            <Setter Property="ItemTemplate" >
                <Setter.Value>
                    <DataTemplate>
                        <Button Content="{Binding}" Padding="15,5" Margin="100,40,0,0"
                                Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}},Path=DataContext.RemoveButtonCommand}"
                                CommandParameter="{Binding}"
                                />
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.Style>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel  Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},Path=ActualWidth}"
                        >                    
            </WrapPanel>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

You will get both vertical and horizontal scrollbars. both adjusting according to height and width of window with the elements in listbox. (please bind your own listbox source)

Upvotes: 0

Filip
Filip

Reputation: 1864

Define WrapPanel as ListBox's ItemsPanel:

            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel ></WrapPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>

Don't forget to set Width or MaxWidth to the wrap panel. Once max width is reached it will start placing content on new line...

Upvotes: 1

Related Questions