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?
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 TemplateBinding
s).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With