How as items listbox Horizontal Alignment Center?
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>
<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.
精彩评论