【发布时间】:2015-07-10 01:16:09
【问题描述】:
如果满足条件,我会在调整表单大小时尝试设置表单的高度。我将其设置为仅允许使用 code provided by in this answer 手动更改表单的宽度。
我有一个 FlowLayoutPanel 显示一组 PictureBox 控件,每个控件的高度固定为 50 像素。最初,表单的高度为 38 (Size.Height - ClientSize.Height) + 50 + 6 (Margin.Top + Margin.Bottom of an image) = 94。
如果控件溢出,默认情况下 FlowLayoutPanel 会将它们向下推送到新行。我想要做的是在发生这种情况时调整表单的大小,或者手动更改表单宽度时,这可能会导致控件跳转到下一行。
以下代码有效,并且在向 FlowLayoutPanel (itemPanel) 添加新控件时调用:
private void ResizeForm()
{
if (itemPanel.Controls.Count < 1) return;
var lastElement = itemPanel.Controls[itemPanel.Controls.Count - 1];
// The Form is the correct size, no need to resize it:
if (lastElement.Bottom + lastElement.Margin.Bottom == itemPanel.Height) return;
Height = 38 + lastElement.Bottom + lastElement.Margin.Bottom;
}
但是,当在我的 SizeChange 事件中调用此方法时,此方法会导致表单在初始高度和新高度之间“闪烁”:
private void MainForm_SizeChanged(object sender, EventArgs e)
{
ResizeForm();
}
我猜是因为设置 Height 会再次触发 SizeChange 事件,但我不知道如何解决这个问题。当我在设置高度后打印出lastElement.Bottom + lastElement.Margin.Bottom 和itemPanel.Height 的值时,它们是相同的,但代码仍然以某种方式达到了这一点。
简而言之,我希望 仅 手动更改表单宽度,但是在添加项目或更改宽度时更改表单的高度,这样FlowLayoutPanel里面的所有控件都可以看到。
【问题讨论】: