2011-04-16 147 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