anthony
anthony

Reputation: 41098

WPF: Programatically adding ListViewItems that expand to the full width of their containing ListView

I have defined a custom ListViewItem contorl in XAML, which we'll call Item.xaml. These custom items are added to a list view using ListView.Items.Add().

How can I add these items so that they will expand horizontally to take up the entire width of their containing ListView? Currently they always remain their original width.

Upvotes: 1

Views: 1023

Answers (2)

anthony
anthony

Reputation: 41098

ChrisWue's answer seemed to work but then I noticed that if I had enough ListViewItems to cause the list to scroll horizontally, the items that were invisible before scrolling down did not stretch horizontally.

I found this MSDN thread that gives the correct approach:

<ListView Name="ListView" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
  <!-- Stretch the contents to match the columns' width: -->
  <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
      <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
  </ListView.ItemContainerStyle>
  ...

Upvotes: 4

ChrisWue
ChrisWue

Reputation: 19020

The ListView has a HorizontalContentAlignment you need to set to Stretch:

<ListView HorizontalContentAlignment="Stretch" ... >

Upvotes: 2

Related Questions