我正嘗試使用自己的佈局引擎創建自定義面板控件。 我需要添加到我的面板的下方添加,並採取全寬(-padding),像下面每一個控制: 帶佈局引擎的自定義面板
下面是我的代碼:
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Layout;
namespace VContainer
{
internal class VerticalFillList : Panel
{
public VerticalFillList()
{
AutoScroll = true;
MinimumSize = new Size(200, 200);
Size = new Size(200, 300);
Padding = new Padding(10);
}
private readonly VerticalFillLayout _layoutEngine = new VerticalFillLayout();
public override LayoutEngine LayoutEngine
{
get { return _layoutEngine; }
}
private int _space = 10;
public int Space
{
get { return _space; }
set
{
_space = value;
Invalidate();
}
}
}
internal class VerticalFillLayout : LayoutEngine
{
public override bool Layout(object container, LayoutEventArgs layoutEventArgs)
{
var parent = container as VerticalFillList;
Rectangle parentDisplayRectangle = parent.DisplayRectangle;
Point nextControlLocation = parentDisplayRectangle.Location;
foreach (Control c in parent.Controls)
{
if (!c.Visible)
{
continue;
}
c.Location = nextControlLocation;
c.Width = parentDisplayRectangle.Width;
nextControlLocation.Offset(0, c.Height + parent.Space);
}
return false;
}
}
}
上面的代碼工作正常,除了一件事: 當我添加控件到我的容器他們正確地添加(新的父母,100%寬度),但當控件的高度大於我的容器高度我得到水平滾動條,但添加一些控件更多的滾動條被刪除。
同樣的事情發生時,我想調整我的容器:
這可怎麼固定?我只需要移除水平滾動條。
當然,所有的改進都是歡迎的。
我不想使用表格佈局或流式佈局,因爲這一個給我什麼時候我需要的。
我需要一個簡單的容器,從上到下對所有子控件進行排序並水平拉伸它們,因此它們需要儘可能多的寬度,因此不需要容器水平滾動條。
button1.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
因此他們將調整水平
但如果它是固定的,你不能把新聞bottons永遠... O_O – MayogaX 2013-03-12 11:43:17
@MayogaX - 我知道:)我只是想表達我的觀點。我將有自定義控件而不是按鈕。我的觀點是要展示我的面板如何運作。大多數情況下,我會在那裏有2-3個控件,但是當用戶添加新控件時,我想避免當水平滾動條可見時出現的情況。調整我的應用程序的同樣的情況。我將在那裏持有最多5-6個控件。以上只是一個演示,以顯示不需要的行爲。 – Misiu 2013-03-12 11:48:35
您正試圖解決Winforms設計師在LayoutEngine類中小心翼翼的問題。像這樣的佈局*雙穩態*。試圖解決它的最典型的結果是在水平滾動條閃爍的情況下陷入無限循環。你有點註定要重塑班級,並最終以同樣的方式去做。 – 2013-03-12 11:50:02