Search code examples
c#wpflistboxgridpanelsizetocontent

WPF Sizing Grid.Row to content


I have a window that uses SizeToContent="WidthAndHeight" and I have a column that has three rows in it. Rows are defines as such:

<Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition />
    <RowDefinition />
</Grid.RowDefinitions>

Content is made up of one other Grid panel per above row. Each of those panels contains a label and a ListBox. ListBox dynamically adds or removes its content. So, it might have one item, or it might have 100 items.

My problem is this: When my application starts, the three above-mentioned rows are sized to the content within them. So it looks pretty neat. If the first row contains only one item in the ListBox, it'll size it just enough to fit those items. The other two rows (if overfilled with content) will split the rest of the space in half and make their scroll bars visible if the user wants to see the overflows in each one. However, as soon as I re-size the main window, the three rows will immediately re-size themselves to where each one will be the exact same height, no matter the amount of content in them.

I tried using Height="Auto" in the row definitions of the outer grid; however, that sizes each row to fit the content precisely, thus causing them to overflow off the screen, without ever enabling the scroll bars.

I've tried every setting that I know of (key: know of) and I couldn't solve it. For now I got rid of SizeToContent so that that weird bug wouldn't happen, but the rows are sized proportional to each other no matter the amount of content in them... and I'd like it the other way. I don't want a static height for each of the rows, but rather having them to re-size themselves dynamically, based on the amount of content in them without going off the screen.

Is there a way to fix this?


Solution

  • To get it right you'll have to make your own custom Panel which handles size distribution smarter than the standard Grid. This project may be a good starting point: ConstrainingStackPanel