Listbox using UniformGrid - Items not centered

2019-06-26 16:01发布

问题:

I have a listbox using UniformGrid for the ItemsPanelTemplate. It is a list of photos. I want the photos to be centered horizontally in the center of each cell of the grid, but it seems that no matter what I do, the images are aligned to the left of each cell. Here is my current XAML:

<Border BorderThickness="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" DockPanel.Dock="Right">
    <ListBox Name="PhotosListBox" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid IsItemsHost="True" HorizontalAlignment="Center"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding Path=photo}" HorizontalAlignment="Center"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Border>

As you can see, I have the Image control in the DataTemplate set to HorizontalAlignment="Center", which I thought would do it, but it's not working.

What am I doing wrong?

回答1:

You need to set HorizontalContentAlignment to Stretch to first allow ListBoxItems to stretch to all available space so that inline control can be aligned at centre accordingly.

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