How to make a WPF ListView no taller than its contents but fit to the window with other controls?

El Zorko picture El Zorko · Mar 16, 2011 · Viewed 20.9k times · Source

I'm trying to arrange a WPF UI as follows:

Mock up

  1. At top of the window are some controls of self-determining height (effectively docked to the top of the window, but as tall as they want to be).
  2. Beneath those controls is a ListView. The ListView may contain a variable number of items each of varying height. The problem: The ListView mustn't be taller than it needs to be. If all the items in the list view will easily fit into the window, I want the ListView to be exactly the height to show all its items (so the window looks like a web page's flowing layout with blank space at the bottom). On the other hand if all ListView items won't fit into the window, I want the whole UI to fit to the window (as if number 3 below was docked to the bottom of the window, and the ListView was filling the available space). This all has to adjust dynamically as the user resizes the window and/or presses buttons which change the list view's contents.
  3. Beneath the ListView are some more controls of self-determining height. These must appear directly under the ListView at all times, with no gap. In particular they mustn't just dock to the bottom of the window if they'll fit directly under the ListView.

Solutions would be very welcome; I've fiddled for some time and managed to get things working except the controls beneath the ListView, by using an outer DockPanel in the window with the first controls docked to the top, and the ListView filling the remaining space but set to VerticalAlignment="Top".

A pure XAML solution would be ideal, but I don't mind code behind if it's unavoidable. Bonus points for a solution which allows multiple such arrangements to be stacked vertically :) Thanks for any help!

Answer

Elad Katz picture Elad Katz · Mar 16, 2011

Try

<Grid VerticalAlignment="Top">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="auto" />

    </Grid.RowDefinitions>

    <Button Content="hello" />
    <ScrollViewer Grid.Row="1" >
    <ListView >
            <ListBoxItem Content="hi" />
            <ListBoxItem Content="hi" />
            <ListBoxItem Content="hi" />
            <ListBoxItem Content="hi" />
            <ListBoxItem Content="hi" />
            <!-- Some Items -->
    </ListView>
    </ScrollViewer>
    <Button Content="hello" Grid.Row="2" />

</Grid>