Search code examples
layoutwindows-phone-7listbox

Center a TextBlock inside a ListBox.ItemTemplate


I'm developing a Windows Phone app.

I have the following XAML code:

<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>

But I couldn't set textblock centered (vertically and horizontally).


Solution

  • There are two ways to achieve this.

    The first solution is to specify the ListBox's ItemContainerStyle inside the ListBox and set the HorizontalContentAlignment property to Center.

    <ListBox ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding Collection}">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="HorizontalContentAlignment" Value="Center"/>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
    

    The second solution is to define a style, and apply the style to the ListBox (so it's reusable).

    <Style x:Key="ListBoxCenteredItemStyle" TargetType="ListBoxItem">                       
        <Setter Property="HorizontalContentAlignment" Value="Center"/>                    
    </Style>
    
    <ListBox 
        ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding Collection}"
        ItemContainerStyle="{StaticResource ListBoxCenteredItemStyle}"/>
    

    The ItemTemplate of a ListBox is just a DataTemplate for displaying each data item. If there is a need to style a single row, the ItemContainerStyle is the guy. :)