我有一行要显示的文本,我想做的只是在显示中文本的标题部分加下划线。请问我该怎么做?
消息:这是客户名称的消息。
其中“消息:”有下划线。
改用RichTextBox!
this.myRichTextBox.SelectionStart = 0;
this.myRichTextBox.SelectionLength = this.contactsTextBox.Text.Length-1;
myRichTextBox.SelectionFont = new Font(myRichTextBox.SelectionFont, FontStyle.Underline);
this.myRichTextBox.SelectionLength = 0;
您可以使用 RichTextBox 控件执行该下划线
int start = rtbTextBox.Text.IndexOf("Message:", StringComparison.CurrentCultureIgnoreCase);
if(start > 0)
{
rtbTextBox.SelectionStart = start;
rtbTextBox.SelectionLength = "Message:".Length-1;
rtbTextBox.SelectionFont = new Font(rtbTextBox.SelectionFont, FontStyle.Underline);
rtbTextBox.SelectionLength = 0;
}
此示例直接使用您在问题中提供的文本。如果将此代码封装在私有方法中并传入标题文本会更好。
例如:
private void UnderlineHeading(string heading)
{
int start = rtbTextBox.Text.IndexOf(heading, StringComparison.CurrentCultureIgnoreCase);
if(start > 0)
{
rtbTextBox.SelectionStart = start;
rtbTextBox.SelectionLength = heading.Length-1;
rtbTextBox.SelectionFont = new Font(rtbTextBox.SelectionFont, FontStyle.Underline);
rtbTextBox.SelectionLength = 0;
}
}
并从您的表格中调用:UnderlineHeading("Message:");
如果要使用富文本框显示文本,可以执行以下操作:
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Underline);
richTextBox1.SelectedText = "Message:";
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Regular);
richTextBox1.SelectedText = " This is a message for Name of Client.";
或者,如果消息是动态的并且标题和文本总是用冒号分隔,您可以执行以下操作:
string message = "Message: This is a message for Name of Client";
string[] parts = message.Split(':');
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Underline);
richTextBox1.SelectedText = parts[0] + ":";
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Regular);
richTextBox1.SelectedText = parts[1];
或者,如果您想在标签中动态显示文本,您可以执行以下操作:
string message = "Message: This is a message for Name of Client";
string[] parts = message.Split(':');
Label heading = new Label();
heading.Text = parts[0] + ":";
heading.Font= new Font("Times New Roman", 10, FontStyle.Underline);
heading.AutoSize = true;
flowLayoutPanel1.Controls.Add(heading);
Label message = new Label();
message.Text = parts[1];
message.Font = new Font("Times New Roman", 10, FontStyle.Regular);
message.AutoSize = true;
flowLayoutPanel1.Controls.Add(message);
只是一个想法,您可以使用蒙版文本框或使用带有下划线的richtextbox 创建自定义控件,并在客户端应用程序中使用它。我听说有可能使用 GDI+ api 创建带下划线的文本框,但不确定。
谢谢马赫什科特卡