[英]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.