Listbox using UniformGrid - Items not centered
Asked Answered
C

1

8

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?

Crappie answered 6/2, 2014 at 18:26 Comment(0)
A
12

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>
Anatase answered 6/2, 2014 at 18:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.