Listbox using UniformGrid - Items not centered

孤人 提交于 2019-12-23 12:06:04

问题


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>


来源:https://stackoverflow.com/questions/21611004/listbox-using-uniformgrid-items-not-centered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!