Sometimes we need to use controls like TextBox, TextBlock etc (that set their width automatically depending on content) in a ListBox’s ItemTemplate. If we need to draw Borders or assign Background colors to each such controls then we may end up having non-equal rows. Here’s a sample markup:
<ListBox ItemsSource="{Binding MyList}" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding}" Background="LightYellow" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here’s the output for the above XAML:
A quick thought would be to assign HorizontalContentAlignment property to Stretch for the TextBox but this wont work. We need to specify this property for the ListBoxItem that encapsulates our DataTemplate. Here’s a quick syntax for doing this using a style:
<Grid>
<Grid.Resources>
<Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</Grid.Resources>
<ListBox Margin="100" ItemsSource="{Binding MyList}"
ItemContainerStyle="{StaticResource ListBoxItemStyle}"
>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding}" Background="LightYellow" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
This should be fine in most case but sometimes we also need to wrap the text as highlighted using red arrows in the above image. Now setting TextWrapping property will have no effect as the TextBox thinks it can take all the horizontal space. This can be solved by disabling the horizontal scroll bar for the ListBox:
<Grid>
<Grid.Resources>
<Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</Grid.Resources>
<ListBox Margin="100" ItemsSource="{Binding MyList}"
ItemContainerStyle="{StaticResource ListBoxItemStyle}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding}"
Background="LightYellow"
TextWrapping="Wrap" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Here’s the final output:
Nice learning for me!



February 1, 2011 at 7:17 PM
Silverlight (and WPF): How to make items stretch horizontally in a ListBox « Mehroz’s Experiments…
Thank you for submitting this cool story – Trackback from DotNetShoutout…
February 4, 2011 at 2:58 AM
Good post. Thanks
May 31, 2011 at 10:55 AM
If datatemplate contain one grid and that grid contain number of textbox divided equally
Please review the below code
When you adding unlimited text the size of textbox increased automatically.
Any solution to stop increase the size of textbox
Thanks in advance
September 23, 2011 at 5:08 PM
Thanks for article. BTW you can also set ListBox property HorizontalContentAlignment=”Stretch”, without adding ItemContainerStyle.
November 30, 2011 at 3:48 PM
Great post, keep going delighting us with new Silverlight tuts.