Multiple colors in a C# .NET label

后端 未结 11 1649
無奈伤痛
無奈伤痛 2020-11-27 03:54

I\'m looking for a way to display multiple colors in a single C#/.NET label. E.g the label is displaying a series of csv separated values that each take on a color dependin

相关标签:
11条回答
  • 2020-11-27 04:21

    Try this,

       labelId.Text = "Successfully sent to" + "<a style='color:Blue'> "  + name + "</a>"; 
    
    0 讨论(0)
  • 2020-11-27 04:22

    As an alternative, you might do this as rtf or html in a suitable control (such as WebBrowser). It would probably take a bit more resources that you'd ideally like, but it'll work fairly quickly.

    0 讨论(0)
  • 2020-11-27 04:24

    I'm using colored labels quite often to mark keywords in red color etc. Like in Phil Wright's answer I use a RichTextBox control, remove the border and set the background color to SystemColors.Control.

    To write colored text the control is first cleared and then I use this function to append colored text:

    private void rtb_AppendText(Font selfont, Color color, Color bcolor, 
                            string text, RichTextBox box)
        {
                // append the text to the RichTextBox control
                int start = box.TextLength;
                box.AppendText(text);
                int end = box.TextLength;
    
                // select the new text
                box.Select(start, end - start);
                // set the attributes of the new text
                box.SelectionColor = color;
                box.SelectionFont = selfont;
                box.SelectionBackColor = bcolor;
                // unselect
                box.Select(end, 0);
    
                // only required for multi line text to scroll to the end
                box.ScrollToCaret();
        }
    

    If you want to run this function with "mono" then add a space before every new colored text, or mono will not set new the color correctly. This is not required with .NET

    Usage:

    myRtb.Text = "";
    rtb_AppendText(new Font("Courier New", (float)10), 
                       Color.Red, SystemColors.Control, " my red text", myRtb);
    rtb_AppendText(new Font("Courier New", (float)10), 
                       Color.Blue, SystemColors.Control, " followed by blue", myRtb);
    
    0 讨论(0)
  • 2020-11-27 04:25

    As per your Question your requirement is simple like lable.Text = "This color is Red", So it have to display text like this "The color is" will be in Blue and "Red" will be red color .. This can be done like this

    lable.Text = "<span style='Color:Blue'>" + " The color is " +"</span>" + "<span style='Color:Red'>"Red"</span>"
    
    0 讨论(0)
  • 2020-11-27 04:27

    I don't think so. You should create one yourself.

    0 讨论(0)
提交回复
热议问题