Windows Phone 7 ListBoxItem Full Horizontal Fill

16 September 2010

Dear Windows Phone 7,

Why is it not enough to set the HorizontalContentAlignment to Stretch on ListBox.ItemContainerStyle in order to allow my ListBoxItems stretch and fill the available space? It apparently works with Silverlight 3.

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

Thank you, Dan DeSousa, for providing the solution - it turns out that you also need to override the entire Template.

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="HorizontalAlignment" Value="Stretch" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <ContentControl x:Name="ContentContainer"
                                             ContentTemplate="{TemplateBinding ContentTemplate}"
                                             Content="{TemplateBinding Content}"
                                             HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

Note that I chose not to include most of the bindings for the Template and only implemented the ones I cared about (Content, ContentTemplate and HorizontalContentAlignment).

Now that the RTM WP7 Dev Tools have been released, there is a pretty high chance that this blog post was already obsolete before I made it. Oh well!

EDIT: And just like that, they fixed it; well, they fixed having to define your own template (it did seem very much like a bug). Now all you need to do for horizontal fill is set the ItemContainerStyle to have HorizontalContentAlignment="Stretch", as in the first code snippet above, and everything will work just fine.

Tags: listbox, listboxitem, silverlight, wp7, XAML

Add a Comment

No Comments