views:

1782

answers:

2

I want to have the ListItems to extend with their orange background the full width of the Listbox.

Currently they are only as wide as the FirstName + LastName.

I've set every element I can to: HorizontalAlignment="Stretch".

I want the background of the ListboxItems to expand as the user stretches the Listbox so I don't want to put in absolute values.

What do I have to do so that the background color of the ListBoxItems fill the width of the ListBox?

<Window x:Class="TestListBoxSelectedItemStyle.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestListBoxSelectedItemStyle"
    Title="Window1" Height="300" Width="300">

    <Window.Resources>
        <local:CustomerViewModel x:Key="TheDataProvider"/>

        <DataTemplate x:Key="CustomerItemTemplate">
            <Border CornerRadius="5" Background="Orange" HorizontalAlignment="Stretch" Padding="5" Margin="3">
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Width="Auto">
                    <TextBlock HorizontalAlignment="Stretch">
                    <TextBlock.Text>
                        <MultiBinding StringFormat="{}{0} {1}">
                            <Binding Path="FirstName"/>
                            <Binding Path="LastName"/>
                        </MultiBinding>
                    </TextBlock.Text>
                    </TextBlock>
                </StackPanel>
            </Border>
        </DataTemplate>

    </Window.Resources>

    <Grid>
        <ListBox ItemsSource="{Binding Path=GetAllCustomers, Source={StaticResource TheDataProvider}}"
                 ItemTemplate="{StaticResource CustomerItemTemplate}"/>
    </Grid>
</Window>
+12  A: 

I'm sure this is a duplicate, but I can't find a question with the same answer.

Add HorizontalContentAlignment="Stretch" to your ListBox. That should do the trick.

Matt Hamilton
Perfect,thanks.
Edward Tanguay
this ones a real DOH when you figure it out :) i tried every combination of stretching for the template but didn't even think about looking at the listbox itself
Simon_Weaver
+4  A: 

I found another solution here, since I ran into both post...

This is from the Myles answer:

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

This worked for me.

Gabriel Mongeon