DCSIMG
Silverlight Quirk: Content Alignment not respected for ListBox - Pavel's Blog
Sign in | Join | Help

Pavel's Blog

Pavel is a software guy that is interested in almost everything
software related... way too much for too little time

Silverlight Quirk: Content Alignment not respected for ListBox

Silverlight and WPF have many similarities, and many differences as well. One of the subtle ones I’ve discovered is with respecting the HorizontalContentAlignment property in a ListBox. Here’s the same application, written in WPF and Silverlight with the following ListBox (bound to a collection of Book objects) and its item template:

   <ListBox HorizontalContentAlignment="Stretch" x:Name="_list">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Red" BorderThickness="2">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto" />
                        </Grid.RowDefinitions>
                        <TextBlock Text="{Binding BookName}" FontSize="20" />
                        <TextBlock Grid.Row="1" Text="{Binding Author}" FontSize="16" Foreground="Blue" />
                    </Grid>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

The results are:

WPF:

image

Silverlight:

image

Not quite the same.

For some reason, Silverlight’s ListBox template does not carry the HorizontalContentAlignment to the inner ListBoxItem objects.

Fortunately, the solution is simple: add an ItemContainerStyle property to the ListBox and set the HorizontalContentAlgnment to “Stretch”:

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

The result:

image

Comments List

# re: Silverlight Quirk: Content Alignment not respected for ListBox

Published at Friday, April 01, 2011 4:46 PM by Jose  

Nice post. It solved my problem in WPF, but it overrides my style template for ListBoxItem (I'm using WPF Themes from Codeplex). How can I avoid overriding the whole style?

# re: Silverlight Quirk: Content Alignment not respected for ListBox

Published at Friday, April 01, 2011 8:55 PM by pavely  

WPF does not need that because HorizontalContentAlignment is respected. However, if you want to make other changes, you can try using style inheritance.

Create your style and add BasedOn="{StaticResource {x:Type ListBoxItem}}".

This should use the existing style and just change/add other stuff.

Leave a Comment

(required) 
(
required
)
 
(optional)
(required) 

Enter the numbers above: