1
votes

I want to strech a ListBox with its ListBoxItem. Streching the ListBox itself isn't a problem. The problem seems to be, to tell the ListBoxItem to use the available space in the ListBox.

<Page.Content>
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Height="200">
        <ListBox VerticalContentAlignment="Stretch" VerticalAlignment="Stretch" Background="Green" ItemsSource="{x:Bind Path=ChessFieldList}" >
            <ListBox.ItemTemplate>
                <DataTemplate >
                    <StackPanel  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Yellow" BorderBrush="Red" BorderThickness="3" >
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Page.Content>

The image below shows the above and expected result.

enter image description here

How can I achieve the expected result?

[Edit] An other and in my opinion the correct solution: Set Width and Height of ItemsControl Children

2
Possible duplicate of Strech ListBox/ItemsControl in UWP - AVK
No thats regarding streching a listbox - this one regards streching listboxitems - Briefkasten

2 Answers

1
votes

This is a common problem. All you need to do is set the HorizontalContentAlignment of the ListBoxItems too:

<ListBox Background="Green" ItemsSource="{x:Bind ChessFieldList}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Background="Yellow" BorderBrush="Red" BorderThickness="3" Height="50">
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Since the StackPanel doesn't contain any content, it won't have any height, so I've just added Height="50" to it for the purpose of this demonstration.

0
votes

Simply add

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
    </Style>
</ListBox.ItemContainerStyle>

If you use grouping, you should include:

<ListView.GroupStyle>
    <GroupStyle HidesIfEmpty="False">
        <GroupStyle.HeaderContainerStyle>
            <Style TargetType="ListViewHeaderItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                <Setter Property="VerticalContentAlignment" Value="Stretch" />
            </Style>
        </GroupStyle.HeaderContainerStyle>
    </GroupStyle>
</ListView.GroupStyle>

It's a bit more than you asked for, but it's a little-known technique.