有没有办法在 ListBox 中为每个项目显示不同的 TextFormat/Style
例子:
Data1:价值
Data2:价值世界
Data3:价值你好
我试过了,但我不能用粗体显示下一个字符串
private void lbDetails_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Rectangle rec = e.Bounds;
string[] temp = lbDetails.Items[e.Index].ToString().Split(':');
e.Graphics.DrawString(temp[0],
new Font("Arial",8, FontStyle.Regular),
Brushes.Black,
rec,
StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
解决方案
private void lbDetails_DrawItem(object sender, DrawItemEventArgs e)
{
try
{
e.DrawBackground();
string[] temp = lbDetails.Items[e.Index].ToString().Split(':');
SizeF prevStr = e.Graphics.MeasureString(temp[0] + ": ", new Font("Arial", 8, FontStyle.Regular));
SizeF nextStr = e.Graphics.MeasureString(temp[1], new Font("Arial", 8, FontStyle.Bold));
RectangleF firstRec = new RectangleF(e.Bounds.X, e.Bounds.Y, prevStr.Width, prevStr.Height);
RectangleF secondRec = new RectangleF(prevStr.Width, e.Bounds.Y, nextStr.Width, nextStr.Height);
e.Graphics.DrawString(temp[0] + ": ",
new Font("Arial", 8, FontStyle.Regular),
Brushes.Black,
firstRec,
StringFormat.GenericDefault);
e.Graphics.DrawString(temp[1],
new Font("Arial", 8, FontStyle.Bold),
Brushes.Black,
secondRec,
StringFormat.GenericDefault);
//e.Graphics.DrawRectangle(Pens.Red, firstRec.X, firstRec.Y, firstRec.Width, firstRec.Height);
e.DrawFocusRectangle();
}
catch (Exception ex)
{
}
}