在ListBox.ItemTemplate中居中放置一个TextBlock
问题描述:
我正在开发一个Windows Phone应用程序。在ListBox.ItemTemplate中居中放置一个TextBlock
我有以下XAML代码:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="GameList" Margin="12" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10,10,10,5" Height="67" HorizontalAlignment="Center" VerticalAlignment="Center" >
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
但我不能设置正文块居中(垂直和水平)。
答
有两种方法可以实现此目的。
第一个解决方案是你指定的ListBox的ItemContainerStyle
内列表框和HorizontalContentAlignment
属性设置为Center
。
<ListBox ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding Collection}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
第二个是,你可以定义一个风格,和样式应用到ListBox(所以它的可重复使用)。
<Style x:Key="ListBoxCenteredItemStyle" TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
<ListBox
ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding Collection}"
ItemContainerStyle="{StaticResource ListBoxCenteredItemStyle}"/>
列表框的ItemTemplate
只是用于显示每个数据项一个DataTemplate。如果你想要设计一个单行,ItemContainerStyle
就是这个人。 :)
感谢您的回答。它很棒! – VansFannel 2011-04-16 17:15:23