How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?
Asked Answered
A

6

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>
Alodee answered 8/5, 2009 at 8:37 Comment(0)
O
518

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.

Ogden answered 8/5, 2009 at 8:44 Comment(11)
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 itselfMonostylous
@ Agile Jedi, do you know of a solution when you DO have custom ListBox Items? Running into that issue myself.Hunfredo
Actually this solution doesn't work in Silverlight for some reason. Gabriel's solution on the other hand doesTommi
When this doesn't work, make sure that there is no Theme that competes for the same behaviour.Content
You also need to set Background="Transparent" on your container inside ItemTemplate. You can check my answer here: https://mcmap.net/q/88249/-how-to-get-xaml-listview-with-full-row-selection-and-correct-themeKhan
This doesn't work on WinRT ListView controls. I've already tried it.Fantasm
@AgileJedi Works for me and mine custom DataTemplated items.Misunderstanding
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".Selflove
Works for me for ListBox in WPF and .Net 4.5 and with using custom ItemsElmerelmina
Custom items do work for me if I set the custom item width to auto.Somnolent
@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.Bellew
L
677

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.

Laciniate answered 27/5, 2010 at 19:30 Comment(6)
@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.Zeena
@RichardB lol My comment was more directed at silverlight, as in why must silverlight be different, and have a broken template compared to WPF.Prostitution
@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.Zeena
To get this to work for a data template within a listView:<ListView.ItemContainerStyle> <Style TargetType="ListViewItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter> </Style> </ListView.ItemContainerStyle>Buttress
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')Spinoza
Also you can try just simply reuse existing theme style as ItemContainerStyle="{StaticResource ListItemStretch}"Poster
O
518

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.

Ogden answered 8/5, 2009 at 8:44 Comment(11)
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 itselfMonostylous
@ Agile Jedi, do you know of a solution when you DO have custom ListBox Items? Running into that issue myself.Hunfredo
Actually this solution doesn't work in Silverlight for some reason. Gabriel's solution on the other hand doesTommi
When this doesn't work, make sure that there is no Theme that competes for the same behaviour.Content
You also need to set Background="Transparent" on your container inside ItemTemplate. You can check my answer here: https://mcmap.net/q/88249/-how-to-get-xaml-listview-with-full-row-selection-and-correct-themeKhan
This doesn't work on WinRT ListView controls. I've already tried it.Fantasm
@AgileJedi Works for me and mine custom DataTemplated items.Misunderstanding
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".Selflove
Works for me for ListBox in WPF and .Net 4.5 and with using custom ItemsElmerelmina
Custom items do work for me if I set the custom item width to auto.Somnolent
@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.Bellew
E
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)

Emma answered 23/8, 2012 at 16:44 Comment(0)
T
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.

Tenderize answered 8/2, 2015 at 22:53 Comment(0)
F
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>
Feign answered 17/2, 2016 at 13:2 Comment(0)
D
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

Darrel answered 17/10, 2016 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.