最近一段时间在网上寻找一个垂直排列的方法,找了很久都没有头绪,于是自己根据控件去微软的在线MSDN上面看资料了,在对某个控件的属性进行详细的研究后,现终于将容器内控件内容及控件自动换行效果实现,其实原理很简单,现将该段代码贴出,希望大家一起研究代码的更精妙之处。如果疑问可以给我留言,希望大家能够多多交流哦(该段代码可以实现,本人小结,仅供参考)。
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
第一步:大家先新建一个form窗体,名字默认为Form1,在该窗体上面添加一个Button,将其文字信息改为“点击跳转”后,即双击该按钮进入代码页面,该页代码内容如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//隐藏当前窗体
this.Hide();
//新建另一个窗体
Form2 form2 = new Form2(ref button1);
form2.Show();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
}
}
如图所示:
保存后再执行第二步。
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
第二步:在form1的项目中再新建一个form,默认名称为Form2,双击该窗体即进入代码编辑页面,该页只要实现窗体自动添加控件,并对其进行垂直布局,代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication3
{
public partial class Form2 : Form
{
//传值
public Button button;
public Form2(ref Button button)
{
this.button = button;
InitializeComponent();//初始化
this.Width = 500;//初始宽度
this.Height = 350;//初始高度
FlowLayoutPanel p1 = new FlowLayoutPanel();//申请一个新的控件
p1.Width = 480;//宽度
p1.Height = 300;//高度
p1.AutoScroll = true; //增加自动滚动条
p1.FlowDirection = FlowDirection.TopDown;//自上而下的流布局
p1.WrapContents = false;//不截断内容
for(int i=1;i<=2;i++)
{
string str = "这是label"+i+",本文是通过测试FlowLayoutPanel中控件的流布局方式进行显示的。此题是将Label中的内容进行换行显示,并采用垂直方式布局,在布局管理方式的过程中采用流中断机制进行控件内容自动换行,希望能够对学习这个方面的朋友有所帮助!";
Label l1 = new Label();
l1.Text = str;
l1.AutoSize = true; //设置AutoSize为可拉伸的
Label l2 = new Label();//用这个空白标签产生换行效果
l2.Text = "";
p1.Controls.Add(l1);//添加标签进容器
p1.GetFlowBreak(l1);//获取流中断
p1.Controls.Add(l2);//将标签添加入容器
p1.GetFlowBreak(l2);//获取流中断
}
for (int n = 1; n <= 3; n++)
{
Button b1 = new Button();
b1.Text = "这是第"+n+"个Button!";
b1.AutoSize = true;
p1.Controls.Add(b1);
p1.GetFlowBreak(b1);//获取流中断
}
this.Controls.Add(p1);
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
}
}
执行后效果如图所示: