[英]C# FlowLayoutPanel and autosize of controls
我在WinForms中遇到flowlayoutpanel的问题。
我想做的是一种聊天程序; 每条消息均由自定义用户控件处理。 无论如何,任何控件都具有相同的行为,因此我将在这个问题中使用一个按钮以使其更加清楚。
为了显示控件,我尝试使用flowlayoutpanel。 我只想显示垂直滚动条,因此我使用事件ClientSizeChanged
修改了子控件的宽度。 这是面板配置:
this.flw_chat.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.flw_chat.AutoScroll = true;
this.flw_chat.AutoScrollMinSize = new System.Drawing.Size(100, 0);
this.flw_chat.BackColor = System.Drawing.Color.LightGray;
this.flw_chat.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.flw_chat.Location = new System.Drawing.Point(12, 27);
this.flw_chat.Name = "flw_chat";
this.flw_chat.Size = new System.Drawing.Size(439, 320);
this.flw_chat.TabIndex = 4;
this.flw_chat.ClientSizeChanged += new System.EventHandler(this.flw_chat_ClientSizeChanged);
这是ClientSizeChanged
事件:
private void flw_chat_ClientSizeChanged(object sender, EventArgs e)
{
if (CurrentFlowWidthWidth != flw_chat.ClientRectangle.Width)
CurrentFlowWidthWidth = flw_chat.ClientRectangle.Width;
foreach (Control c in flw_chat.Controls)
{
c.Width = CurrentFlowWidthWidth - c.Margin.Horizontal;
}
}
这是添加控件的代码(例如按钮)
var temp = new Button();
temp.Text = "AAA";
if (CurrentFlowWidthWidth != flw_chat.ClientRectangle.Width)
flw_chat_ClientSizeChanged(null, null);
temp.Width = CurrentFlowWidthWidth - temp.Margin.Horizontal;
flw_chat.Controls.Add(temp);
现在,该行为有些奇怪。 我认为控件应占据面板的每个像素。 当显示垂直滚动条时,所有控件都必须调整为新尺寸,而在调整面板大小时,控件必须跟随新尺寸。
这是我通常看到的行为。 但是有两个例外:
您知道为什么会这样吗? 您将如何解决?
我无法完全消除水平滚动条,但是使用此代码,我几乎可以解决您发现的两个问题。 快速调整大小时,水平滚动条会闪烁,但不会保留在屏幕上。 并且当垂直滚动条出现时,它会进行另一种布局以删除水平滚动条。
这是我修改后的ClientSizeChanged事件处理程序:
private void flw_chat_ClientSizeChanged(object sender, EventArgs e)
{
if (CurrentFlowWidthWidth != flw_chat.ClientSize.Width || flw_chat.HorizontalScroll.Visible)
{
CurrentFlowWidthWidth = flw_chat.ClientSize.Width;
foreach (Control c in flw_chat.Controls)
c.Width = CurrentFlowWidthWidth - c.Margin.Horizontal - 4;
}
}
这是我修改后的代码以添加新控件:
private void AddControl_Click(object sender, EventArgs e)
{
var temp = new Button();
temp.Text = "AAA";
if (CurrentFlowWidthWidth != flw_chat.ClientSize.Width)
flw_chat_ClientSizeChanged(null, null);
temp.Width = CurrentFlowWidthWidth - temp.Margin.Horizontal - 4;
flw_chat.Controls.Add(temp);
if (flw_chat.HorizontalScroll.Visible)
flw_chat.PerformLayout();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.