转自博客:
http://blog.csdn.net/langyuewu/article/details/38865423
最近有个项目要修改,看完后果断决定重构,里面很多不规范的地方,布局大部分都是计算出来的,但是基本没有采用布局控件,不能自适应,其中有类似九宫格的布局方式,放在WPF,那真是一个控件秒秒钟能搞定的事情,好多年没做winform了,拿回来还是很容易上手。在winform里,最适合就是TableLayoutPanel了,本来简单的内容想不写,不过可能有人需要用到就放上来。
废话说那么多了,进入正题,其实动态布局很简单,就是SizeType.Percent,大小100F就好了,代码如下。
-
private void InitLayoutDemo()
-
{
-
TableLayoutPanel demoLayoutPanel = new TableLayoutPanel();
-
demoLayoutPanel.Dock = DockStyle.Fill;
-
this.Controls.Add(demoLayoutPanel);
-
int row = 3, col = 3;
-
DynamicLayout(demoLayoutPanel, row, col);
-
for (int i = 0; i < row; i++)
-
{
-
for (int j = 0; j < col; j++)
-
{
-
Button btn = new Button();
-
btn.Text = string.Format("({0},{1})", i, j);
-
btn.Dock = DockStyle.Fill;
-
demoLayoutPanel.Controls.Add(btn);
-
demoLayoutPanel.SetRow(btn, i);
-
demoLayoutPanel.SetColumn(btn, j);
-
}
-
}
-
}
-
-
-
-
-
-
-
-
private void DynamicLayout(TableLayoutPanel layoutPanel, int row, int col)
-
{
-
layoutPanel.RowCount = row;
-
for (int i = 0; i < row; i++)
-
{
-
layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
-
}
-
layoutPanel.ColumnCount = col;
-
for (int i = 0; i < col; i++)
-
{
-
layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
-
}
-
}
注意,我这里TableLayoutPanel也是动态添加的,如果TableLayoutPanel是已经拖放到Form里面的,把原来的行列删剩一行一列,且保证都是百分比100%。
阅读(4932) | 评论(0) | 转发(0) |