Recently I was using a ListBox in Silverlight together with the WrapPanel. Idea wasn’t too complicated, just a list and a button to add items. Each time the button was pressed, some items was generated in code behind and added to the list. If there was no space left for the new item, the wrap panel was expected to do his job, wrap the line and vertical scroll-bar was expected to be showed. So far so good… but it was not working as expected.
So the code was looking more less like this one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource ViewModel}" Width="400" Height="400"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Button Grid.Row="0" Content="Add Item" Command="{Binding AddItemCommand}" Width="75" Height="25" Margin="5" /> <ListBox Grid.Row="1" ItemsSource="{Binding Items}" VerticalAlignment="Top" Height="150" Width="300" Margin="5" ScrollViewer.VerticalScrollBarVisibility="Visible"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <toolkit:WrapPanel /> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.ItemTemplate> <DataTemplate> <Button Content="{Binding Name}" Width="75" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> |
Nothing special, a button, a list box, wrap panel for items template and vertical scroll-bar. Should work – but unfortunately result was far from expected:
Hmm… ok .. so what we do now? Well, there are two solutions for this problem:
- We can disable horizontal scrolling what would force wrapping panel to do its job.
1ScrollViewer.HorizontalScrollBarVisibility="Disabled" - Or we can modify a Template of the ListBox and add a ScrollViewer there:
1234567<ListBox.Template><ControlTemplate><ScrollViewer><ItemsPresenter /></ScrollViewer></ControlTemplate></ListBox.Template>
Now – everything works is as expected:
I know, I know – it’s nothing complicated – it’s more like a memo for myself – I hope next time when I will forget it, it will save me some time 😉