This is a mirror of official site: http://jasper-net.blogspot.com/

Silverlight (and WPF): How to make items stretch horizontally in a ListBox

| Sunday, August 5, 2012
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:
Inline image 1

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:

QR: Inline image 2

Posted via email from Jasper-net

0 comments: