Update: I know, I fucked up the Horizontal/Vertical naming inside the listboxes in the screenshots.
We all know WPF’s a beast when it comes to UI customization. With things like ItemTemplates, ItemPanels and Bindings we can completely customize the layout and behavior of existing controls without affecting the core fundamentals (the properties and events the control exposes). This type of powerful functionality has captured my hearts and is the main reason why I love technologies like WPF and Silverlight. In this post we’ll keep it simple and take a look at how to create a horizontal ListBox.
Turning a ListBox into a horizontal one can easily be done by changing the ItemsPanel property. The ItemsPanel property of a control needs to be a panel control (Grid, DockPanel, StackPanel, WrapPanel,…), and it will determine the layout of items within that collection. Think of the ItemsPanel as the parent container, and each of the ListItems as childs within that container. When we set the ItemsPanel property to that of a StackPanel with horizontal orientation, we get a horizontal listbox!
Below’s the XAML code to achieve this. I’ve also added a ItemContainerStyle which gets applied to each item within the ListBox, adding a bit of a padding.
<ListBox Height="96" HorizontalAlignment="Left" Margin="10,10,0,0" Name="listBox2" VerticalAlignment="Top" Width="479"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal" /> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Padding" Value="30 0 30 0" /> </Style> </ListBox.ItemContainerStyle> <ListBoxItem Content="Vertical Item 1" /> <ListBoxItem Content="Vertical Item 2" /> <ListBoxItem Content="Vertical Item 3" /> <ListBoxItem Content="Vertical Item 4" /> <ListBoxItem Content="Vertical Item 5" /> </ListBox>