Get ListBox to resize with window, but not resize with content

BrianReturns picture BrianReturns · Feb 8, 2012 · Viewed 15.5k times · Source

There must be an elegant solution to this problem, but I can't find anything online. I have a grid that has one column and row with width/height *, containing a ListBox. I have my Window SizeToContents set to WidthAndHeight to allow the window to resize to the proper size for each set of UI widgets/fonts. When I add items to the ListBox, it resizes, causing the window to grow.

I want the ListBox to resize if I change the size of the window, but if I add content that is longer than the width of the ListBox, I want the scrollbar to appear and not for it to grow, causing the Window to grow. If I set explicit sizes for the Window and set SizeToContent to Manual (the default), it works as I intend.

Is there any way to size the window to the contents at startup and continue to have the ListBox grow with the window size, but not with its content?

Answer

FTLPhysicsGuy picture FTLPhysicsGuy · May 4, 2017

Following Potecaru Tudor's suggestion, I solved a similar issue by wrapping the ListBox in another container and binding the ListBox's Height to the ActualHeight of the container.

Here is a XAML code snippet to help:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Border x:Name="HeightHelperPanel" Grid.Row="0">
        <ListBox ItemsSource="{Binding Path=FileNameCollection}"
                 MinHeight="60"
                 Height="{Binding Path=ActualHeight, ElementName=HeightHelperPanel}"/>
    </Border>
</Grid>

Basically, the Border container doesn't grow when its content grows, but it will stay stretched to the height of the grid row. The grid row will fill up any space the containing window will allow it, but will not want to force any height constraints on the window. The ListBox's height is therefore constrained to the height of the Border.

Hope that helps anyone else who has had this somewhat frustrating issue.