ListView ItemTemplate 100% width

kiewic picture kiewic · Sep 5, 2013 · Viewed 21.6k times · Source

How can I make content of each ListView item expands to 100% width when using a DataTemplate?

I have tried HorizontalContentAlignment="Stretch" in the ListView and HorizontalAlignment="Stretch" in the DataTemplate, but nothing seems to work, content is still aligned to the left.

I have something like this:

<ListView x:Name="questionsView" Background="{StaticResource ApplicationPageBackgroundThemeBrush}" HorizontalContentAlignment="Stretch">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Border Background="BlueViolet" HorizontalAlignment="Stretch">
                <Grid HorizontalAlignment="Stretch">
                    <TextBlock Text="{Binding}" />
                    <TextBlock HorizontalAlignment="Right">16 minutes ago</TextBlock>
                </Grid>
            </Border>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

I guess there is one more layer between the ListView and the ItemTemplate.

Answer

kiewic picture kiewic · Sep 5, 2013

I got it. Setting the ListView.ItemContainerStyle with a HorizontalContentAlignment setter makes the trick. I.e.:

<ListView x:Name="questionsView" Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Border Background="BlueViolet">
                <Grid HorizontalAlignment="Stretch" Margin="0">
                    <TextBlock Text="{Binding}" />
                    <TextBlock HorizontalAlignment="Right">16 minutes ago</TextBlock>
                </Grid>
            </Border>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListView.ItemContainerStyle>
</ListView>