【问题标题】:How to change the color of a part of a label c# [duplicate]如何更改标签c#的一部分的颜色[重复]
【发布时间】:2020-04-24 07:46:17
【问题描述】:

早上好,

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

我的标签的文字,比如是这个:

河马

我有一个包含这个的字符串:

波波塔

我希望我的标签是黑色的“Hi”,红色的“popota”,最后是黑色的“mus”。

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

我希望你能帮助我:)

【问题讨论】:

标签: c#


【解决方案1】:

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);
}

【讨论】:

  • 谢谢谢谢谢谢谢谢谢谢谢谢你,再次感谢你这个非常详细的答案,效果非常好!很少得到这样的回应:))))))))))))))
猜你喜欢
  • 2018-06-16
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
相关资源
最近更新 更多