见图片我想减少每行控件之间的水平空间。
此 Windows 形成 FlowLayoutPanel。我已经用红色突出显示了一个单元格以显示当前的间距。
通过从面板派生,您可以很容易地创建自己的自定义 FlowLayoutPanel。
虽然下面的代码为水平和垂直设置了一个统一的边框,但您可以很容易地修改为每个水平和垂直间距都有一个属性。
public class FlowPanel : Panel
{
protected int _TileBorder;
public int TileBorder
{
get
{
return this._TileBorder;
}
set
{
this._TileBorder = value;
this.RearrangeControls(this, this.TileBorder);
}
}
public FlowPanel()
{
this.AutoScroll = true;
}
public FlowPanel(int tileBorder)
{
this.AutoScroll = true;
this.TileBorder = tileBorder;
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
this.RearrangeControls(this, this.TileBorder);
}
protected override void OnControlAdded(ControlEventArgs e)
{
base.OnControlAdded(e);
this.RearrangeControls(this, this.TileBorder);
e.Control.SizeChanged += new EventHandler(this.Control_SizeChanged);
}
protected override void OnControlRemoved(ControlEventArgs e)
{
base.OnControlRemoved(e);
this.RearrangeControls(this, this.TileBorder);
e.Control.SizeChanged -= new EventHandler(this.Control_SizeChanged);
}
protected void RearrangeControls(Panel p, int border)
{
int num = border;
int num2 = border;
int num3 = 0;
bool flag = true;
foreach (Control control in p.Controls)
{
if (control != null)
{
num3 = ((control.Height > num3) ? control.Height : num3);
if (flag)
{
num += control.Width + border;
control.Location = new Point(border, border);
flag = false;
}
else
{
if (num + control.Width + 2 * border > p.Width)
{
num2 += num3 + border;
control.Location = new Point(border, num2);
num = border + (control.Width + border);
num3 = control.Height;
}
else
{
control.Location = new Point(num, num2);
num += control.Width + border;
}
}
}
}
}
private void Control_SizeChanged(object sender, EventArgs e)
{
this.RearrangeControls(this, this.TileBorder);
}
}
现在我看了一下,RearrangeControls 方法对我来说确实看起来有点匆忙,但我相信你可以让它变得更好!