Search code examples
c#listboxscrollbarwrappanel

how to display vertical scrollbar in ListBox with WrapPanel


I have a ListBox which displays its items in a WrapPanel. The ListBox itself is embeddded in Border. But the more items I put into the ListBox, the larger window gets. How can I prevent that and display the vertical scrollbar instead?

I found several other posts but nothing worked so far.

ListBox

            <Border Background="WhiteSmoke" BorderBrush="Gray" BorderThickness="4" Margin="5"> 
            <ListBox Background="Transparent" BorderThickness="0" Height="Auto" 
                     ItemsSource="{Binding Path=Snapshots, RelativeSource={RelativeSource AncestorType=Demo:CameraCanvas}}"
                     SelectedItem="{Binding Path=Snapshots.SelectedSnapshot, RelativeSource={RelativeSource AncestorType=Demo:CameraCanvas}}"
                     ScrollViewer.VerticalScrollBarVisibility="Auto"
                     ScrollViewer.CanContentScroll="True"
                     >
                <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel 
                            Width="{Binding (FrameworkElement.ActualWidth), 
                            RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}" 
                            ItemWidth="{Binding (ListView.View).ItemWidth, RelativeSource={RelativeSource AncestorType=ListView}}"
                            MinWidth="{Binding ItemWidth, RelativeSource={RelativeSource Self}}" 
                            ItemHeight="{Binding (ListView.View).ItemHeight, RelativeSource={RelativeSource AncestorType=ListView}}" />
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Border CornerRadius="5" Background="WhiteSmoke" BorderBrush="Gray" BorderThickness="2" Margin="5" Padding="2">
                            <StackPanel Orientation="Vertical">
                                <Image Source="{Binding Path=Image, UpdateSourceTrigger=PropertyChanged}" Width="64" Height="64" Stretch="Uniform" StretchDirection="Both" />
                            </StackPanel>
                        </Border>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
            </Border>

Solution

  • Put the ListBox in a DockPanel, the dockpanel should be constrainted in size.

    read the following msdn topic Panels Overview