Windows窗体动态布局 [英] WIndows Forms dynamic layout

查看:121
本文介绍了Windows窗体动态布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义用户控件,可以执行我的应用程序.

I have a custom usercontrol which does the work of my app.

我需要一次在表单上拥有可变数量的用户控件,该数量在运行时是已知的.

I need to have a variable number of my usercontrols on my form at once, the number is known at runtime.

我希望每个窗口都具有完整的客户端宽度,并且所有控件都应填满窗口,大小相等,例如.如果有两个,则每个都是客户端高度的一半-如果三个,则每个都是客户端高度的三分之一.

I want each one to be full client width, and all controls to fill the window, equal size... eg. if there are two, then each are half the client height - if three, then each are one third of the client height.

并且布局应该随着主窗口的大小而调整大小.我不希望用户能够通过调整主窗口的大小来调整控件的大小(这样就可以拆分容器了)

And the layout should resize as the main window resizes. I don't want the user to be able to resize the controls other than by resizing the main window (so a split container is out)

我尝试使用TableLayoutPanel来执行此操作,但是当我将GrowStyle属性设置为TableLayoutPanelGrowStyle.AddRows并添加控件时,行数不会改变.

I've tried to use the TableLayoutPanel to do this but when I set the GrowStyle property to TableLayoutPanelGrowStyle.AddRows, and add my controls, the number of rows doesn't change.

当然,这种布局方案不难实现吗?我似乎无法弄清楚?

Surely this layout scheme isn't hard to achieve? I can't seem to figure it out?

谢谢

推荐答案

布局易于计算,然后很难使TLP获利.这是一种在设计器中效果很好的控件,但是在控件数量无法预测的情况下,它会很尴尬.

It the layout is simple to calculate then it gets to be pretty hard to make TLP pay off. Which is a control that works very well in the designer but is pretty awkward when you have an unpredictable number of controls.

这也可以很好地工作,减少了很多代码,也减少了控制UI速度的控制:

This will work fine as well, a lot less code and one less control to slow your UI down:

    protected override void OnResize(EventArgs e) {
        for (int ix = 0; ix < Controls.Count; ++ix) {
            int y1 = this.ClientSize.Height * ix / Controls.Count;
            int y2 = this.ClientSize.Height * (ix + 1) / Controls.Count;
            Controls[ix].Bounds = new Rectangle(0, y1, this.ClientSize.Width, y2-y1);
        }
        base.OnResize(e);
    }
    protected override void OnLoad(EventArgs e) {
        OnResize(e);
        base.OnLoad(e);
    }

这篇关于Windows窗体动态布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆