我正在尝试使用我自己的布局引擎创建自定义面板控件。 我需要添加到我的面板的每个控件都添加到下面并采用全宽(-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% 宽度),但是当控件的高度大于我的容器高度时,我得到水平滚动条,但在添加几个控件后,更多滚动条被删除。
当我想调整我的容器大小时,同样的事情发生了:
如何解决这个问题?我只需要删除那个水平滚动条。
当然欢迎所有的改进:)
我不想使用表格布局或流式布局,因为这个布局会在我需要时准确地提供给我。
我需要一个简单的容器,它可以从上到下排列所有子控件并水平拉伸(stretch)它们,以便它们占据尽可能多的宽度,因此不需要容器水平滚动条。
最佳答案
不幸的是,这是一个工作示例,它没有使用您的布局引擎类。它仅依赖于 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;
}
}
}
关于c# - 带有布局引擎的自定义面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15359969/