Make portion of a Label's Text to be styled bold

前端 未结 12 622
离开以前
离开以前 2020-11-30 12:12

Is there any way to make a part of a label.text to be bold?

label.text = \"asd\" + string;

Would like the string

12条回答
  •  不知归路
    2020-11-30 12:58

    The following class illustrates how to do it by overriding OnPaint() in the Label class of WinForms. You can refine it. But what I did was to use the pipe character (|) in a string to tell the OnPaint() method to print text before the | as bold and after it as normal text.

    class LabelX : Label
    {
        protected override void OnPaint(PaintEventArgs e) {
            Point drawPoint = new Point(0, 0);
    
            string[] ary = Text.Split(new char[] { '|' });
            if (ary.Length == 2) {
                Font normalFont = this.Font;
    
                Font boldFont = new Font(normalFont, FontStyle.Bold);
    
                Size boldSize = TextRenderer.MeasureText(ary[0], boldFont);
                Size normalSize = TextRenderer.MeasureText(ary[1], normalFont);
    
                Rectangle boldRect = new Rectangle(drawPoint, boldSize);
                Rectangle normalRect = new Rectangle(
                    boldRect.Right, boldRect.Top, normalSize.Width, normalSize.Height);
    
                TextRenderer.DrawText(e.Graphics, ary[0], boldFont, boldRect, ForeColor);
                TextRenderer.DrawText(e.Graphics, ary[1], normalFont, normalRect, ForeColor);
            }
            else {
    
                TextRenderer.DrawText(e.Graphics, Text, Font, drawPoint, ForeColor);                
            }
        }
    }
    

    Here's how to use it:

    LabelX x = new LabelX();
    Controls.Add(x);
    x.Dock = DockStyle.Top;
    x.Text = "Hello | World";       
    

    Hello will be printed in bold and world in normal.

提交回复
热议问题