C# 中的多行標籤
本教程將介紹在 C# 中建立多行標籤的方法。
使用 C# 中的 Label.AutoSize 屬性建立多行標籤
Label.AutoSize 屬性指定標籤是否可以自動調整其大小以適合 C# 中顯示的文字。Label.AutoSize 屬性具有布林值,如果我們希望我們的標籤自動調整大小以適合顯示的文字,則必須將其設定為 true;如果我們不想讓我們的標籤自動調整大小,則必須將其設定為 false 以適合正在顯示的文字。然後,我們可以使用 C# 中的 Control.MaximumSize 屬性設定標籤的最大尺寸。下面的程式碼示例向我們展示瞭如何使用 C# 中的 Label.AutoSize 屬性建立多行標籤。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace multi_line_label {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
string data = "This is some data that we want to display";
label1.Text = data;
label1.AutoSize = true;
label1.MaximumSize = new Size(50, 0);
}
}
}
輸出:

在上面的程式碼中,我們使用 C# 中的 Label.AutoSize 和 Control.MaximumSize 屬性建立了一個多行標籤。
使用 C# 中的 Panel 方法建立多行標籤
我們還可以使用 Panel 控制元件在 C# 中建立多行標籤。我們可以在面板中放置所需的標籤,然後為面板處理 ClientSizeChanged 事件。每當面板內部控制元件的大小發生更改時,都會呼叫 ClientSizeChanged 事件。我們可以使用 C# 中的 Label.MaximumSize 屬性來調整標籤的大小。以下程式碼示例向我們展示瞭如何使用 C# 中的 Panel 方法建立多行標籤。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace multi_line_label {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
string data = "This is some data that we want to display";
label1.Text = data;
label1.AutoSize = true;
}
private void panel1_ClientSizeChanged(object senderObject, EventArgs eventArguments) {
label1.MaximumSize =
new Size((senderObject as Control).ClientSize.Width - label1.Left, 10000);
}
}
}
輸出:

我們在上述程式碼中通過將標籤放置在面板內並在 C# 中處理面板內的 ClientSizeChanged 事件來建立了多行標籤。我們首先將 Label.AutoSize 屬性指定為 true,然後在面板的 ClientSizeChanged 事件中指定標籤的最大尺寸。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn