Trey Balut
Trey Balut

Reputation: 1395

Windows 8 ListBox TextAlignment Not Working

I have a ListBox - ListBox.ItemTemplate - DataTemplate xaml setup and I'm trying to center the text in the ListBox (TextBlock) . The TextAlignment property doesn't seem to work. Any ideas? Here is my code:

  <ListBox x:Name="listBox1" HorizontalAlignment="Left" Height="520" Margin="190,220,0,0" VerticalAlignment="Top" Width="295" SelectionChanged="listBox1_SelectionChanged" FontSize="20" FontWeight="Bold" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding name}" FontSize="25" Foreground="Black" TextAlignment="Center"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Upvotes: 0

Views: 331

Answers (1)

Jeff Brand
Jeff Brand

Reputation: 5633

The ListBox uses a StackPanel internally to contain each itemtemplate By default, the itemtemplate is sized only big enough to contain its children. In your template, the textblock is only going to size itself to fit the bound text, thus, there is no "center" because the bounding textblock exactly matches the size of the text. Set the size of your textblock explicitly or you can add the following to your listbox (or declare as a reusable style in your page resoruces)

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

Upvotes: 1

Related Questions