#424 – Getting Data-Bound Items in a ListBox to Be a Consistent Size
November 7, 2011 4 Comments
I demonstrated earlier how to add some rich content to a ListBox using data binding.
The problem with this is that the items don’t line up vertically. We use several StackPanel elements in the data template, which autosize to fit their content. We’d like them to autosize, but to use that same size across all rows, for each column.
We can share sizes between entries using the Grid.IsSharedSizeScope and SharedSizeGroup properties.
<ListBox ItemsSource="{Binding MovieList}" SnapsToDevicePixels="True" Grid.IsSharedSizeScope="True"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" Margin="0,0,0,5"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition SharedSizeGroup="Col1"/> </Grid.ColumnDefinitions> <Image Source="{Binding Image}" /> </Grid> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition SharedSizeGroup="Col2"/> </Grid.ColumnDefinitions> <StackPanel Orientation="Vertical"> <Label Content="{Binding Title}" FontWeight="Bold"/> <Label Content="{Binding Year}"/> </StackPanel> </Grid> <Border BorderBrush="Black" BorderThickness="0.5"/> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition SharedSizeGroup="Col3"/> </Grid.ColumnDefinitions> <StackPanel Orientation="Vertical"> <Label Content="Actors:"/> <Label Content="{Binding ActorLead}" Margin="10,0"/> <Label Content="{Binding ActressLead}" Margin="10,0"/> </StackPanel> </Grid> <Border BorderBrush="Black" BorderThickness="0.5"/> <StackPanel Orientation="Vertical"> <Label Content="Director:"/> <Label Content="{Binding Director}" Margin="10,0"/> </StackPanel> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>