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:


 

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:

And here’s the output:

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:

Here’s the final output: