|
最近一段時間在網上尋找一個垂直排列的方法,找了很久都沒有頭緒,於是自己根據控制項去微軟的線上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();
}
}
}
執行後效果如圖所示:
|