Nostromo
Nostromo

Reputation: 1274

HorizontalAlignment or VerticalAlignment don't work as expected

Everytime I think I begin to understand how WPF is working, it's doing something (or doesn't do it) and I don't understand why. May you can shed a light.

I'd like to place some numbers on the screen, the numbers should be surrounded by a Border and the complete Border should have a colored background (not just the bounding box of the TextBlock containing the numbers.)

So I did something like this:

<ListBox ItemsSource="{Binding Numbers}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="3" Columns="4" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderThickness="1" BorderBrush="Black">
                <TextBlock Text="{Binding .}" />
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

But although I declared HorizontalAlignment and VerticalAlignment as Stretch the border (and a background I didn't include in the example) only cover the bounding box of the TextBlock, not the complete cell of the UniformGrid. Am I missing something here?

Upvotes: 0

Views: 109

Answers (1)

FrankM
FrankM

Reputation: 1117

This is because the list box item's content presenter by default does not stretch. Therefore, you have to add this to your ListBox:

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

Upvotes: 1

Related Questions