WPF: WrapPanel in ItemsPanelTemplate expands list width

Hallgeir picture Hallgeir · Jul 2, 2010 · Viewed 7.5k times · Source

I have a listbox defined like this:

    <ListBox.ItemTemplate>
        <DataTemplate>
            <ItemsControl>
                <!-- Contents here -->
            </ItemsControl>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

My problem is this: This list is contained in a grid control, and should use all the available space of that cell its contained in, but it shouldn't force the parent to allocate MORE space. But what happens is that once the wrap panel fills up, instead of actually wrapping the items to the next line (as it should), it just expands the width of the listbox, and in the process forces the parent grid to resize as well.

How can I get the wrap panel to respect the size of its parent, and not force it to expand its size?

Thanks in advance!

edit: One more thing. I can set the width of the wrappanel explicitly to make it wrap, but I would like the wrappanel to have the same size as the listbox.

Answer

Wallstreet Programmer picture Wallstreet Programmer · Jul 2, 2010

Set ScrollViewer.HorizontalScrollBarVisibility="Disabled" and the WrapPanel will wrap.

<Grid>
    <ListBox
        ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>
</Grid>