jack_the_beast
jack_the_beast

Reputation: 1971

positioning text within ItemTemplate - Windows Phone 8

I always got problems with elements positioning in windows phone. hope someone can help me: I've a Listbox dinamically populatem from code behind:

<ListBox Name="list" Grid.Row="1" HorizontalAlignment="Center">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"  Style="{StaticResource list_service_item}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>

the style is defined in App.xaml:

<Style x:Key="list_service_item" TargetType="TextBlock">
        <Setter Property="FontSize" Value="25"/>
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="Foreground" Value="Peru" />
        <Setter Property="TextWrapping" Value="Wrap"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="Margin" Value="0 0 0 5"/>
    </Style>

and looks like is working correctly except for the alignment property.

if the listbox items have the same length all works well, but if one of them is longer all the others align themselves to the start of the longer item instead of remain centered:

enter image description here

how can i solve this?

Upvotes: 1

Views: 172

Answers (2)

Sheridan
Sheridan

Reputation: 69959

How about using the TextBlock.TextAlignment property?:

<Style x:Key="list_service_item" TargetType="TextBlock">
    <Setter Property="FontSize" Value="25" />
    <Setter Property="FontWeight" Value="Bold" />
    <Setter Property="Foreground" Value="Peru" />
    <Setter Property="TextWrapping" Value="Wrap" />
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="TextBlock.TextAlignment" Value="Center" /><!--<<< Used here-->
    <Setter Property="Margin" Value="0 0 0 5"/>
</Style>

Disclaimer: This works for WPF, but I can't guarantee that it works for Windows Phone 8

UPDATE >>>

Ok, after seeing your picture I would agree that it is not working as you expect. However, I think that It could be more of a case that the items are not placed correctly. You can try this:

<ListBox HorizontalContentAlignment="Center" ... />

If that does not work, you could try setting that property to Stretch so that the items fill the space and then that could give the TextBlocks the to centre themselves:

<ListBox HorizontalContentAlignment="Stretch" ... />

Upvotes: 0

Daniel
Daniel

Reputation: 11054

You need to make the ItemContainer for each ListBoxItem stretch to the width of the ListBox:

<ListBox.ItemContainerStyle>
  <Style TargetType="ListBoxItem">
    <Setter Property="HorizontalContentAlignment"
            Value="Stretch" />
  </Style>
</ListBox.ItemContainerStyle>

Upvotes: 1

Related Questions