WPF how to stretch listbox content item

Something I’ve been search for, for quit some times is how to stretch the content of a listbox in WPF. If you add a textbox to a listbox item, the textbox will only take as much space as it needs (to make it more visible I’ve add a border and a backgroundbrush):

Default listbox content

Of course I’ve tried to set the HorizontalAlignment to stretch, which didn’t work. And I’ve set the width, but that doesn’t work if the listbox is resized. The solution is actually quite simple:

      <ListBox HorizontalContentAlignment="Stretch">
            <ListBoxItem>
                <Border BorderThickness="2" BorderBrush="Black" Background="Yellow">
                    <TextBlock Text="Item1"/>
                </Border>
            </ListBoxItem>
            <ListBoxItem>
                <Border BorderThickness="2" BorderBrush="Black" Background="Yellow">
                    <TextBlock Text="Long item 2"/>
                </Border>
            </ListBoxItem>
            <ListBoxItem>
                <Border BorderThickness="2" BorderBrush="Black" Background="Yellow">
                    <TextBlock Text="Very very looooong item 3"/>
                </Border>
            </ListBoxItem>
            <ListBoxItem>
                <Border BorderThickness="2" BorderBrush="Black" Background="Yellow">
                    <TextBlock Text="Item4"/>
                </Border>
            </ListBoxItem>
 
        </ListBox>

Note the HorizontalContentAlignment=”Stretch”
With this result:

Streched listbox content

Comments are closed.