Search code examples
c#wpfimagedata-bindinglistbox

c# WPF display Listbox with 3 columns in each row


I would like to display three columns in each row with some images and a text. But whatever i try i cannot get the ListBox to display the Items horizontaly. Only the Stackpanel inside the Listbox itself.

<ListBox Name="lsbox" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    ItemsSource="{Binding Cards}"
    SelectedItem="{Binding SelectedItem}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Margin="3" Text="{Binding Name}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                <Image Width="200" Height="300" Margin="100" Source="{Binding Path}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                <UniformGrid Columns="3"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Images are displayed below each other

I previously was able to get the images to display next to each other like this:

<ListBox Name="lsbox" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Grid.Row="1">
                <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <UniformGrid Columns="3"/>
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
                <Image Source="33bfedbf836836cd81108e1e3e57a8e1.jpg"/>
                <Image Source="33bfedbf836836cd81108e1e3e57a8e1.jpg"/>
                <Image Source="33bfedbf836836cd81108e1e3e57a8e1.jpg"/>
            </ListBox>

3 Images are displayed horizontaly in each row

But like this I could only set the image source manually and not with Bindings to set the Items or Image Source. I just started with wpf so i am really at my limits here.

Best Regards Robin


Solution

  • Configure the item panel the same way as before, then remove the <UniformGrid /> from inside the data template:

    <ListBox Name="lsbox" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
        ItemsSource="{Binding Cards}"
        SelectedItem="{Binding SelectedItem}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="3"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Margin="3" Text="{Binding Name}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    <Image Width="200" Height="300" Margin="100" Source="{Binding Path}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>