WPF ListBox that lays out its items horizontally

Andrew Shepherd picture Andrew Shepherd · Aug 18, 2009 · Viewed 57.9k times · Source

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.

Answer

adatapost picture adatapost · Aug 18, 2009

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