Using a DataTemplate for a ListBox so that it fills the width of the Listbox

I'm trying to use a DataTemplate in a ListBox.

My code looks something like this:

<!-- In an appropriate resources area -->
<DataTemplate ... >
  <StackPanel Background="...">
    <TextBlock Text="{Binding ... }" />
    <TextBlock Text="{Binding ... }" />
    <TextBlock Text="{Binding ... }" />
  </StackPanel>
</DataTemplate>

and further on I have a ListBox defined that uses this DataTemplate for its ItemTemplate

What's driving me nuts is that the StackPanel clearly only occupies the minimum amount of space required to hold its content. It doesn't stretch to fill the entire space of the listbox item, so the background color only partially fills the item.

What (obvious, I'm sure) thing am I missing I have tried setting the StackPanel HorizontalAlignment to Stretch, but that makes no difference. There seems to be no way of saying <StackPanel Width="As big as the listbox'" />, which is what I need.



Answer this question

Using a DataTemplate for a ListBox so that it fills the width of the Listbox

  • Asa Whillock

    And then the insanity lifts, and it's as simple as:

    <Style TargetType="{x:Type ListBoxItem}">
      <
    Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </
    Style>

    Doh!


  • Manni

    You can also use HorizontalAlignment="Stretch" to stretch individual elements rather than all children of a container.  There are vertical versions as well.  You can also use other values that move the contents to the left, center, or right.

    Michael


  • Using a DataTemplate for a ListBox so that it fills the width of the Listbox