58
votes

I'm trying to write a WPF application for displaying images from a selection. I want to display all of the available images in a banner along the top of the window, and display the main selected image in the main window for further processing.

If I wanted the list on the Left of the window, displaying the images vertically, I can do this quite elegantly using databinding.

    <ListBox 
        Name="m_listBox"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding}"            
        >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding}" Width="60" Stretch="Uniform" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Is there a straightforward way I can make this horizontal instead of vertical? The main requirements of a solution is:

  • The items are populated using databinding
  • The selected item is changed simply by the user clicking it.
3

3 Answers

128
votes

WrapPanel

 <ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBoxItem>listbox item 1</ListBoxItem>
    <ListBoxItem>listbox item 2</ListBoxItem>
    <ListBoxItem>listbox item 3</ListBoxItem>
    <ListBoxItem>listbox item 4</ListBoxItem>
    <ListBoxItem>listbox item 5</ListBoxItem>
</ListBox>

WPF Tutorial

21
votes

The default ItemsPanel for the ListBox control is a VirtualizingStackPanel, so if you want the normal, default experience for the control but just have it laid out horizontally, you should specify this (and change the orientation).

Example:

<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel IsItemsHost="True" Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>
1
votes

Here is example of StackPanel. Horizontal Breadcrumb with Mvvm binding

 <ItemsControl
            x:Name="tStack"
            Grid.Row="1"
            Grid.Column="0"
            Height="40"
            Background="Red"
            ItemsSource="{Binding BreadCrumbs}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button
                        Margin="5"
                        CommandParameter="{Binding .}"
                        Command="{Binding BreadcrumbClickCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=DataContext.BreadcrumbClickCommand}"
                        Content="{Binding Name}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>