#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>
Hello sean I’m Fevzi at Computer Enginering department from Turkey. Can you give your email adress for me ? I have some quasetions about Wpf to you ?
Actually, maybe more efficient for you to post any WPF questions here on the blog. Then other people have a chance to respond to them.
thank you so much! at last I am free to move on with my project…
Hi Sean, great articles. One thing I an wrestling with is (if using your example) is if one of the grids contains an ItemsControl with several columns. I have Grid.IsSharedSizeScope set for the Listbox (so the Listbox column iterations are the same) and also for the ItemsControl (so the ItemsControl column iterations are the same). Is there a way to “carry” the ItemsControl values over the Listbox iterations? Currently the listbox iterations are correct and each individual ItemsContol is correct but the ItemsControl are not uniform throughout the list. Thanks…