开发者

How as items listbox Horizontal Alignment Center?

开发者 https://www.devze.com 2023-01-22 23:17 出处:网络
A have listbox <ListBox> <ListBox.ItemTemplate> <DataTemplate> <DockPanel> 开发者_C百科<Button Content=\"{Binding name_trainer}\" Tag=\"{Binding idPersonTrainer}\" DockPane

A have listbox

<ListBox>
    <ListBox.ItemTemplate>
    <DataTemplate>
        <DockPanel>
    开发者_C百科    <Button Content="{Binding name_trainer}" Tag="{Binding idPersonTrainer}" DockPanel.Dock="Top" HorizontalAlignment="Center">
        </Button>
        </DockPanel>
    </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

How as items listbox Horizontal Alignment Center?


<ListBox HorizontalContentAlignment="Center">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding yourstuff}" FontSize="72"/>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>


<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel HorizontalAlignment="Center"/>
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>


The accepted answer is right, however I needed a bit more: not only to center, but also to horizontally stretch the items. Just changing HorizontalAlignment to Stretch didn't work, so, here's how it's done:

<ItemsPanelTemplate>
    <StackPanel HorizontalAlignment="Stretch">
        <StackPanel.Resources>
            <Style TargetType="ListBoxItem">
                <Setter Property="HorizontalContentAlignment" Value="Center"/>
            </Style>
        </StackPanel.Resources>
    </StackPanel>
</ItemsPanelTemplate>


You may have to center the DockPanel, rather than the data inside it. I've seen this behavior with StackPanel, because the panel shrinks to the contents. The centering ends up working properly, but in the wrong context.

0

精彩评论

暂无评论...
验证码 换一张
取 消