我正在尝试使用自己的布局引擎创建自定义Panel控件。
我需要添加到我的面板中的每个控件都添加到下面并采用全宽(-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%宽度),但是当控件的高度大于我的容器高度时,我得到水平滚动条,但是在添加几个控件之后,更多滚动条被删除。
当我想调整容器大小时会发生同样的事情:
如何解决这个问题?我只需要删除那个水平滚动条。
当然欢迎所有改进:)
我不想使用表格布局或流程布局,因为这样可以在我需要时准确提供。
我需要一个简单的容器,从上到下对所有子控件进行排序并将它们水平拉伸,这样它们就可以获得尽可能宽的宽度,因此不需要容器水平滚动条。
答案 0 :(得分:3)
这是一个工作示例,遗憾的是,它不使用您的Layout Engine类。它只依赖于OnControlAdded和OnControlRemoved方法,并锚定和设置AutoScrollMinSize属性以专门确保水平滚动条永远不会出现:
internal class VerticalPanel : Panel {
private int space = 10;
public int Space {
get { return space; }
set {
space = value;
LayoutControls();
}
}
protected override void OnControlAdded(ControlEventArgs e) {
base.OnControlAdded(e);
LayoutControls();
}
protected override void OnControlRemoved(ControlEventArgs e) {
base.OnControlRemoved(e);
LayoutControls();
}
private void LayoutControls() {
int height = space;
foreach (Control c in base.Controls) {
height += c.Height + space;
}
base.AutoScrollMinSize = new Size(0, height);
int top = base.AutoScrollPosition.Y + space;
int width = base.ClientSize.Width - (space * 2);
foreach (Control c in base.Controls) {
c.SetBounds(space, top, width, c.Height);
c.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
top += c.Height + space;
}
}
}
答案 1 :(得分:-1)
你可以在你的按钮上设置AnchorProperty:
button1.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
所以他们将被横向调整大小