首页 > 解决方案 > 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?

标签: wpf

解决方案


这是因为默认情况下列表框项目的内容展示器不会拉伸。因此,您必须将其添加到您的 ListBox:

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

推荐阅读