Thursday, November 11, 2010

WPF: Making ListBoxItems stretch the width of the ListBox

This is unbelievably hard for something which must be universally desired.

By default, ListBoxItems occupy the width required by their contents, not by the width of the containing ListBox.  This causes your optimistically formatted columns in each ListBox to fail to align.

Instead, add this in the Resources section:


<Style x:Key="StretchingListBoxItemStyle" TargetType="ListBoxItem">
  <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>


and add ItemContainerStyle="{StaticResource StretchingListBoxItemStyle}" to your ListBox attributes.

Strewth.

No comments: