How to make a list item horizontally stretched?

Here is a window with a simple list:

2010_02_13% 20ListBoxItemWidth% 20screenshot.png

The code is straightforward:

<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 element is different. Looks like "Auto." I tried different ways, but did not find to make objects stretch horizontally without hard coding the width.

How do I?

+7
wpf listbox
source share
1 answer

ListBox has a property called HorizontalContentAlignment . I think setting up Stretch will do the trick. Although, if you reformat the ListBox and / or change its ItemContainerStyle , make sure that the value of this property is applied where necessary (via TemplateBinding s).

+14
source share

All Articles