How can you make the items in your DataTemplate stretch over the full width?

Stretching ListViewItems over full width in Universal Apps.

The next image shows a Windows Phone 8 ListView. Every ListViewItem is a container for a TextBox and a CheckBox where the CheckBox needs to be right-aligned.

result

By default, the following XAML:

<ListView x:Name="list" Margin="20">
<ListView.ItemTemplate>
<DataTemplate>
    <Grid Background="#22FF0000" Margin="0,0,0,2">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="50" />
        </Grid.ColumnDefinitions>
        <TextBlock Text="{Binding Name}" VerticalAlignment="Center" FontSize="20" Margin="20,0,10,0" />
        <CheckBox Grid.Column="1" IsChecked="{Binding IsManager}" VerticalAlignment="Center" />
    </Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Will give the following result:

wrong

The red background was put here to indicate that the items don’t stretch over the full width.

Solution: Add an ItemContainerStyle to stretch items

Add the following XAML to your ListView children:

<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>

And this is how the result looks like:

Stretched

This solution works on both Windows Phone 8 and Windows 8.

Written by Loek van den Ouweland on 2015-02-11.
Questions regarding this artice? You can send them to the address below.