Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listbox using UniformGrid - Items not centered

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?

like image 445
JoeMjr2 Avatar asked Feb 06 '14 18:02

JoeMjr2


1 Answers

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>
like image 200
Rohit Vats Avatar answered Nov 14 '22 17:11

Rohit Vats