2011-04-16 46 views
0

我正在开发一个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> 

但我不能设置正文块居中(垂直和水平)。

回答

5

有两种方法可以实现此目的。

第一个解决方案是你指定的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就是这个人。 :)

+1

感谢您的回答。它很棒! – VansFannel 2011-04-16 17:15:23

相关问题