Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretch empty WPF ListView to take the remaining space

I always have problems with a ListView inside a dynamic layout control like a Stackpanel.

Right now I have a Window with a Stackpanel as Root-Control. The Stackpanel streches perfectly and takes the complete window. Inside the StackPanel are some other controls like textboxes and button all aligned fine.

The last Object is a ListView. I want the ListView to take the remaining space from the StackPanel but it does not. Even with VerticalAlignment="Stretch" I only get the column headers. The ListView only grows when items are added to it. So I have to set the ListView height manually.

How can I make the ListView fill the remaining space in a StackPanel even when it is empty?

like image 752
TalkingCode Avatar asked May 28 '10 09:05

TalkingCode


2 Answers

This has nothing to do with the ListView. It is the StackPanel's "fault". In a StackPanel the child items always consume only the space they need (in the direction of the orientation of the StackPanel). That's how the StackPanel is designed. Use a DockPanel instead, there you can make the last item fill up all the space that is left over using LastChildFill="true" (true is default, so no need to explicity specify it).

<DockPanel Background="Green">
    <Button DockPanel.Dock="Top">Text</Button>
    <ListView DockPanel.Dock="Top">
        <ListView.View>
            <GridView>
                <GridViewColumn/>
            </GridView>
        </ListView.View>
    </ListView>     
</DockPanel>
like image 196
bitbonk Avatar answered Oct 16 '22 01:10

bitbonk


How about using a grid? Grids are made for this kind of layout. The DockPanel is a good suggestion too.

  <Grid>  
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="*"/>
     </Grid.RowDefinitions>

   <TextBlock Grid.Row="0" Text="row1"/>
   <Button Grid.Row="1" Content="row2"/>
   <ListView Grid.Row="2">
     <ListViewItem Content="Text"/>
     <ListViewItem Content="Text1"/>
     <ListViewItem Content="Text2"/>
   </ListView>
  </Grid>

The important part is the Height="*", this tells the row to take up all available space, you can leave this out if you want as it is the default behaviour.

like image 22
Lee Treveil Avatar answered Oct 16 '22 03:10

Lee Treveil