简体   繁体   中英

How to adjust WrapPanel height dynamically based on content?

I'm developing a WPF application. In this application, I have a Window which contains a WrapPanel. Inside the WrapPanel are a series of StackPanels which have varying heights, but all the same width. The number and size of the StackPanels is not known at design time (they are generated dynamically).

These StackPanels normally stack fine on top of each other, and then "wrap" to another column when there is no more room in the WrapPanel. To achieve this, I had to set a fixed height for my WrapPanel (with the height set to "Auto", it would continue down the page instead of wrapping to another column). However, when by chance I have a StackPanel that is too large to fit in the WrapPanel height, it is simply truncated. An image of this situation is below.

在此处输入图片说明

My question is, can I query the height of each StackPanel before I Show() this to the user, and set the WrapPanel height based on the largest StackPanel? Is there a better way to do this?

First, have you ensured that this issue is not caused by the WrapPanel reaching its maximum available dimensions (ie if its size is being constrained by its parent Window or element)? Because if this is the case, then you'll need to either look at restructuring your overall layout, or wrap it in a ScrollViewer.

If the above is not the case, and the WrapPanel has plenty of room to 'grow', this does indeed seem like a strange issue. You say the StackPanels are generated dynamically. So in your code, you must be calling myWrapPanel.Children.Add(stackPanel) . After this line of code, you could try adding something like the following:

myWrapPanel.Height = myWrapPanel.Children.Cast<FrameworkElement>().Max(e => e.ActualHeight);

EDIT: just realized this will only work if a single StackPanel takes up the entire height, as in your image. but perhaps it will start you on the right track!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM