Search code examples
c#.netwpfdatatemplate

WrapPanel behavior within ListBox: vertical to fill available space and then wrap horizontally


I have a listbox within a custom scrollviewer that provides some unique visual styles. The Listbox ItemsPanel is a WrapPanel, and all of the listbox items are 100x100. The Listbox height is static and will not be changed. The desired layout is this: fill available space vertically before wrapping like so:

enter image description here

I've played with both Orientation variables of the WrapPanel, and have not been able to achieve the desired layout. I suspect this has something to do with the fact that I'm wrapping the Listbox in a custom ScrollViewer control and the listbox can't calculate available space properly. Since the height is static, I feel like i should be able to make this work (it only scroll horizontally, and the outer custom scrollviewer should be doing the scrolling). Here is the current setup slimmed down:

<controls:CustomScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Hidden">
    <controls:CustomScrollViewer.Template> .... </controls:CustomScrollViewer.Template>
    <ListBox Height="...">

        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>

        <ListBox.ItemTemplate>
            <DataTemplate> .... </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.Resources>
            <Style TargetType="{x:Type ListBoxItem}"> .... </Style>
        </ListBox.Resources>
    </ListBox>
</controls:CustomScrollViewer>

Instead of wrapping the Listbox in a scrollviewer, is there a way to get the ListBox to use the custom scrollviewer internally? Or how can I achieve the desired layout?


Solution

  • By hard-coding the Height of the WrapPanel, with the Orientation set to Vertical, I was able to achieve the desired layout.

    I would still be curious to a solution that uses the custom scrollviewer to replace the scrollviewer that would be internally in the listbox.