有没有办法让label.text的一部分变得粗体?
label.text = "asd" + string;希望string部分为粗体。
是可能的,如何做到这一点呢?
发布于 2010-01-14 17:48:45
WinForms不允许这样做。
发布于 2010-01-14 18:17:42
下面的类演示了如何通过重写WinForms的Label类中的OnPaint()来完成此操作。您可以对其进行改进。但我所做的是在字符串中使用竖线字符(|)来告诉OnPaint()方法将|之前的文本作为粗体打印,将它之后的文本作为普通文本打印。
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);
}
}
}下面是它的使用方法:
LabelX x = new LabelX();
Controls.Add(x);
x.Dock = DockStyle.Top;
x.Text = "Hello | World"; Hello将以粗体格式打印,而world以普通格式打印。
发布于 2010-01-14 17:54:59
WebForms
使用Literal控件,并在所需文本部分周围添加<b>标记:
_myLiteral.Text = "Hello <b>big</b> world";
Winforms
有两个选项:
Label和在OnPaint()方法中进行您自己的自定义绘制。第二个选择已经是answered。
https://stackoverflow.com/questions/2063263
复制相似问题