Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 273
BrianReturns Avatar asked Feb 08 '12 19:02

BrianReturns


3 Answers

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.

like image 171
FTLPhysicsGuy Avatar answered Nov 20 '22 11:11

FTLPhysicsGuy


HorizontalAlignment="Stretch" VerticalAlignment="Stretch"

like image 34
vinoth Avatar answered Nov 20 '22 10:11

vinoth


This is the intended behavior resulted from setting the SizeToContent property to WidthAndHeight as described here.

What you might do is binding the Width and the Height of the ListBox to the ActualWidth and ActualHeight properties of its container, or use a converter and bind them directly to the Window's respective properties.

like image 1
Avram Tudor Avatar answered Nov 20 '22 11:11

Avram Tudor