减少FlowLayoutPanel中的水平空间

时间:2012-09-13 05:17:08

标签: winforms

参见图片我想在每行控件之间水平缩小空间。

此Windows形成FlowLayoutPanel。我已经突出显示一个红色的单元格,以显示当前的间距。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以通过从面板派生来轻松创建自己的自定义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方法对我来说看起来有些匆忙,但我相信你可以让它变得更好!