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