Simple WPF: ListBox Items Stretching To Fill Width

Here’s a fairly common question that can be solved fairly easily. Sometimes when you have a ListBox of Items you would like for those items to stretch the available width of the ListBox. Sounds pretty straightforward right? Given we have something similar to the below XAML :

<ListBox x:Name="SearchResults"

                     BorderBrush="{x:Null}"

                     ScrollViewer.VerticalScrollBarVisibility="Visible"

                     SelectedItem="{Binding SearchResultsSelectedItem}">

                <ListBox.ItemTemplate>

                    <DataTemplate>

                        <Grid>

                            <Grid.ColumnDefinitions>

                                <ColumnDefinition Width="30" />

                                <ColumnDefinition Width="*"/>

                                <ColumnDefinition Width="30" />

                            </Grid.ColumnDefinitions>

                            <Button Grid.Column="0" Margin="0"

                                        Content="Press Me"/>

                            <TextBlock Grid.Column="1" Text="Some Text"/>

                            <Button Grid.Column="2" Margin="0"

                                        Content="No Press Me"/>

                        </Grid>

                    </DataTemplate>

                </ListBox.ItemTemplate>

            </ListBox>

You would think that this would get the trick done right? After all I told the Grid in the DataTemplate that the second column needed to have a expansible width that would take up any of the left-over space from the button columns. Unfortunately this won’t work and the items will only be sized to the largest one in the set. So if you want it to stretch the entire width of the ListBox’s ItemPanel you need to use the following attribute in the ListBox itself:

 

HorizontalContentAlignment="Stretch" 

This will cause the contents to take up the entire width of the ListBox.

 

Cheers!

AJ