Stretching ListBoxItem Content to fit a Listbox
Have you wanted to completely fill, stretch, or maximize the content of a ListBoxItem in WPF to match the width of the viewport (the scrollable area)? I have -- and it took me far too many searches to find it AGAIN yesterday (so, I'm posting it here so I'll be able to find it again when I forget this again). By default, a ListBoxItem in a listbox is only as wide as the content needs to be. So, if you're trying to align content to the right side for example, it may not end up where you want it.
You only need to do two things:
- Create a Style that sets that the HorizontalContentAlignment property to Stretch.
- Use the style created in step 1 as the value for the ItemContainerStyle property of the ListBox.
See below for an example:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Page.Resources> <Style x:Key="StretchedContainerStyle" TargetType="{x:Type ListBoxItem}"> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> </Style> </Page.Resources> <Grid> <ListBox ItemContainerStyle="{StaticResource StretchedContainerStyle}"> <ListBox.Items> <ListBoxItem> <Grid> <TextBlock>My listbox item 1</TextBlock> </Grid> </ListBoxItem> <ListBoxItem> <Grid Background="Silver"> <TextBlock>My listbox item 1</TextBlock> </Grid> </ListBoxItem> </ListBox.Items> </ListBox> </Grid> </Page>
Paste the above into XAMLPad. Try removing the ItemContainerStyle to see the impact of setting the HorizontalContentAlignment property.