378

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>
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

6 Answers6

672

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.

Community
  • 1
  • 1
Gabriel Mongeon
  • 7,251
  • 3
  • 32
  • 35
  • @CameronMacFarland The reason for silverlight, at least in my case, is because the IT Admin staff couldn't figure out how to deploy WPF/Winform apps using Active Directory, and we wanted a clean deployment scenario that didn't depend on us Sneakernetting the updates. – Richard B Jul 23 '12 at 13:53
  • @RichardB lol My comment was more directed at silverlight, as in why must silverlight be different, and have a broken template compared to WPF. – Cameron MacFarland Jul 23 '12 at 14:17
  • @CameronMacFarland ah... no worries. After doing a Silverlight app, and struggling with the ServiceReferences.ClientConfig file, I'm set that I'll avoid (like the plague) ever developing another Silverlight application again. It was a cool idea, but just not impressive. – Richard B Jul 24 '12 at 16:47
  • 1
    To get this to work for a data template within a listView: – Christopher Cook Sep 15 '14 at 02:12
  • Error: BindingExpression path error: 'Width' property not found on Project.CustomElement, Project.WindowsPhone, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. BindingExpression: Path='Width' DataItem=Project.CustomElement, Project.WindowsPhone, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'; target element is 'Windows.UI.Xaml.Controls.Grid' (Name='null'); target property is 'Width' (type 'Double') – Black Cid Apr 10 '15 at 07:28
  • Also you can try just simply reuse existing theme style as ItemContainerStyle="{StaticResource ListItemStretch}" – Yury Schkatula May 15 '15 at 13:47
517

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. Just be careful with auto-complete because it is so easy to get HorizontalAlignment by mistake.

Sergei Tachenov
  • 24,345
  • 8
  • 57
  • 73
Matt Hamilton
  • 200,371
  • 61
  • 386
  • 320
  • 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 Jul 22 '10 at 00:44
  • 1
    @ Agile Jedi, do you know of a solution when you DO have custom ListBox Items? Running into that issue myself. – eoldre May 09 '11 at 15:35
  • 11
    Actually this solution doesn't work in Silverlight for some reason. Gabriel's solution on the other hand does – TimothyP May 23 '11 at 08:55
  • When this doesn't work, make sure that there is no Theme that competes for the same behaviour. – Patrice Calvé Sep 27 '12 at 18:25
  • You also need to set Background="Transparent" on your container inside ItemTemplate. You can check my answer here: http://stackoverflow.com/a/19164395/259172 – virious Oct 03 '13 at 16:31
  • 7
    This doesn't work on WinRT ListView controls. I've already tried it. – uSeRnAmEhAhAhAhAhA Jan 20 '14 at 23:31
  • @AgileJedi Works for me and mine custom DataTemplated items. – AgentFire Sep 15 '14 at 09:35
  • 3
    This works fine on custom lists (Windows, not Silverlight), just be careful with auto complete when writing the xaml. If you write "Horiz.." you will get "HorizontalAlignment" not "HorizontalContentAlignment". It is pretty easy to select the the first suggestion, since both are using "Stretch". – Jarle Bjørnbeth Nov 20 '14 at 12:31
  • Works for me for ListBox in WPF and .Net 4.5 and with using custom Items – Hunv Nov 24 '15 at 12:33
  • 1
    Custom items do work for me if I set the custom item width to auto. – Lensflare Dec 09 '15 at 17:08
  • 1
    @Jarle, spot on! That's what bit me, and I haven't even noticed. Edited the answer, as it's too important to stay in the comments. – Sergei Tachenov Jul 23 '16 at 07:55
81

If your items are wider than the ListBox, the other answers here won't help: the items in the ItemTemplate remain wider than the ListBox.

The fix that worked for me was to disable the horizontal scrollbar, which, apparently, also tells the container of all those items to remain only as wide as the list box.

Hence the combined fix to get ListBox items that are as wide as the list box, whether they are smaller and need stretching, or wider and need wrapping, is as follows:

<ListBox HorizontalContentAlignment="Stretch" 
         ScrollViewer.HorizontalScrollBarVisibility="Disabled">

(credits for the scroll bar idea)

Community
  • 1
  • 1
Roman Starkov
  • 59,298
  • 38
  • 251
  • 324
0

Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.

Sangeetha
  • 485
  • 2
  • 9
  • 24
0

The fix for me was to set property HorizontalAlignment="Stretch" on ItemsPresenter inside ScrollViewer..

Hope this helps someone...

<Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBox">
                    <ScrollViewer x:Name="ScrollViewer" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" Padding="{TemplateBinding Padding}" HorizontalAlignment="Stretch">
                        <ItemsPresenter  Height="252" HorizontalAlignment="Stretch"/>
                    </ScrollViewer>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
itzmebibin
  • 9,199
  • 8
  • 48
  • 62
Ivica Marincic
  • 149
  • 1
  • 6
0

I also had the same problem, as a quick workaround, I used blend to determine how much padding was being added. In my case it was 12, so I used a negative margin to get rid of it. Now everything can now be centered properly