如何更改标签 c# 的一部分的颜色



早上好,

我想实现一个系统来搜索列表中的项目。 我制作了这需要的代码,但我遇到了一个问题。

例如,我的标签文本是这样的:

希波波塔莫斯

我有一个包含以下内容的字符串:

波塔

我希望我的标签是黑色的">

Hi",红色的">popota",最后是黑色的">mus"。

我在互联网上搜索了很多东西,真的有一段时间了,所以我找到了一个论坛。

我希望你能帮助我:)

Label控件本身不支持多种颜色,但RichTextBox控件支持多种颜色!您可以将其属性设置为看起来像标签。

例如,要使其看起来像标签:

private void Form1_Load(object sender, EventArgs e)
{
// Make the RichTextBox look and behave like a Label control
richTextBox1.BorderStyle = BorderStyle.None;
richTextBox1.BackColor = System.Drawing.SystemColors.Control;
richTextBox1.ReadOnly = true;
richTextBox1.Text = "Hipopotamus";
// I added a small, blank Label control to the form which I use to capture the Focus
// from this control, so the user can't see the caret or select/highlight/edit text
richTextBox1.GotFocus += (s, ea) => { lblHidden.Focus(); };
}

然后,通过设置选择开始和长度以及更改所选颜色来突出显示搜索词的方法:

private void HighlightSearchText(string searchText, RichTextBox control)
{
// Make all text black first
control.SelectionStart = 0;
control.SelectionLength = control.Text.Length;
control.SelectionColor = System.Drawing.SystemColors.ControlText;
// Return if search text isn't found
var selStart = control.Text.IndexOf(searchText);
if (selStart < 0 || searchText.Length == 0) return;
// Otherwise, highlight the search text
control.SelectionStart = selStart;
control.SelectionLength = searchText.Length;
control.SelectionColor = Color.Red;
}

为了进行测试并显示用法,我向窗体中添加了一个txtSearch文本框控件,并在TextChanged事件中调用上述方法。运行窗体,并在文本框中键入以查看结果:

private void txtSearch_TextChanged(object sender, EventArgs e)
{
HighlightSearchText(txtSearch.Text, richTextBox1);
}

最新更新