A ListBox with Columns
So here is some XAML to make a ListBox display its data in columns, for those cases where you don't want to use a ListView. Hope someone finds this useful.
First, we set up a ControlTemplate for the ListBox that gives us some headers in a UniformGrid, which is a grid whose columns are all the same width:
<ControlTemplate x:Key="CityListBoxTemplate"> <StackPanel> <UniformGrid Columns="4" TextBlock.Foreground="Silver" TextBlock.FontSize="9pt"> <TextBlock Text="City"/> <TextBlock Text="State"/> <TextBlock Text="Postcode"/> <TextBlock Text="Population"/> </UniformGrid> <StackPanel IsItemsHost="True"/> </StackPanel> </ControlTemplate>
Next, we set up a DataTemplate for each item in the ListBox that also uses a UniformGrid. I've made the first column bold and slightly bigger in this particular list.
<DataTemplate x:Key="CityListItemTemplate"> <UniformGrid Columns="4" Margin="0,2,0,2"> <TextBlock Text="{Binding City}" FontSize="10pt" FontWeight="Bold"/> <TextBlock Text="{Binding State}" FontSize="9pt" /> <TextBlock Text="{Binding Postcode}" FontSize="9pt" /> <TextBlock Text="{Binding Population}" FontSize="9pt" /> </UniformGrid> </DataTemplate>
Lastly, we set up a style so you can just apply this style to the ListBox, and both of the above templates will be applied for you:
<Style TargetType="ListBox" x:Key="CityListStyle" BasedOn="{StaticResource {x:Type ListBox}}"> <Setter Property="Template" Value="{StaticResource CityListBoxTemplate}"/> <Setter Property="ItemTemplate" Value="{StaticResource CityListItemTemplate}"/> </Style>
So now all you have to do is apply this style to your ListBox, like this:
<ListBox ItemsSource="{StaticResource myCities}" Style="{StaticResource CityListStyle}"/>
Give it a try and see how you go!