WrapPanel not wrapping as ListBox ItemsPanel

When using a WrapPanel as the ItemsPanel for a ListBox as such

<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
... <!-- ListBoxItems -->
</ListBox>

The WrapPanel may not wrap the items as expected. This is because of WPF’s width and height sizing issue. Depending on the type of Panel that the ListBox is contained in e.g. StackPanel, Grid, etc the width of the ListBox will be resolved differently. If the width of the ListBox is allowed to resize infinitely e.g. “size to fit contents” in the Orientation of the WrapPanel, then WrapPanel will never need to wrap and a scrollbar will appear on the ListBox to allow scrolling in that direction instead.

The ScrollBars that appear on the ListBox is due to a ScrollViewer internal to ListBox. You can use the attached property of the ScrollViewer to disable the scrollbar so that the ListBox is forced to wrap e.g.

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
... <!-- ListBoxItems -->
</ListBox>

Alternatively, as mentioned before, tweak the width resolution mechanism up the parent tree to get the desired result.