Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make list item horizontally stretched?

Tags:

wpf

listbox

Here is a window with a simple list:

The code is straight-forward:

<Window x:Class="Wpf_List.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>


        <Border BorderBrush="Black" BorderThickness="2" Grid.Column="1">
            <ListBox>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <!--HorizontalAlignment="Stretch" below has no effect :(-->
                        <Border CornerRadius="5" BorderBrush="DarkRed" SnapsToDevicePixels="True" BorderThickness="1"
                            Margin="1" Padding="4,2"
                            HorizontalAlignment="Stretch"
                            >
                            <TextBlock Text="{Binding}"/>
                        </Border>
                    </DataTemplate>
                </ListBox.ItemTemplate>

                <sys:String>First</sys:String>
                <sys:String>Second</sys:String>
                <sys:String>Some item with a long name</sys:String>
            </ListBox>
        </Border>
    </Grid>
</Window>

The width of each item is different. Looks like "Auto". I tried various ways, but didn't found one to make items stretch horizontally without hard-coding the width.

How do I?

like image 740
bohdan_trotsenko Avatar asked Feb 13 '10 20:02

bohdan_trotsenko


1 Answers

ListBox has a property named HorizontalContentAlignment. I think setting it to Stretch will do the trick. Although if you re-template the ListBox and/or change its ItemContainerStyle make sure value of this property is applied where necessary (via TemplateBindings).

like image 136
arconaut Avatar answered Nov 10 '22 19:11

arconaut