如何使ListBox中的某些项目变为粗体?

在Visual c#Express Edition中,是否可以在ListBox中创建一些(但不是全部)项目? 我在API中找不到任何类型的选项。

您需要将列表框的DrawMode更改为DrawMode.OwnerDrawFixed。 查看msdn上的这些文章:
DrawMode枚举
ListBox.DrawItem事件
Graphics.DrawString方法

另请在msdn论坛上查看此问题:
关于ListBox项目的问题

一个简单的例子(两个项目 – Black-Arial-10-Bold):

public partial class Form1 : Form { public Form1() { InitializeComponent(); ListBox1.Items.AddRange(new Object[] { "First Item", "Second Item"}); ListBox1.DrawMode = DrawMode.OwnerDrawFixed; } private void ListBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), new Font("Arial", 10, FontStyle.Bold), Brushes.Black, e.Bounds); e.DrawFocusRectangle(); } } 

要添加到MindaugasMozūras的解决方案,我遇到了一个问题,我的e.Bounds不够大,文字被切断了。 要解决此问题(感谢此处的post),您将覆盖OnMeasureItem事件并将DrawMode更改为DrawMode.OwnerDrawVariable

在设计师:

 listBox.DrawMode = DrawMode.OwnerDrawVariable; 

处理程序:

 void listBox_MeasureItem(object sender, MeasureItemEventArgs e) { e.ItemHeight = 18; } 

解决了我的高度切断文字的问题。

以下是演示相同的代码。

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { foreach (FontFamily fam in FontFamily.Families) { listBox1.Items.Add(fam.Name); } listBox1.DrawMode = DrawMode.OwnerDrawFixed; // 属性里设置} private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), new Font(listBox1.Items[e.Index].ToString(), listBox1.Font.Size), Brushes.Black, e.Bounds); //e.DrawFocusRectangle(); } } } 

样本输出

一个更通用的例子,它使用发送者,并且实际上尊重前景色(例如,如果选择了项目,或者用户使用了另一种颜色集,其中黑色前景色实际上不可读)和当前ListBox字体:

  private void listBoxDrawItem (object sender, DrawItemEventArgs e) { Font f = e.Font; if (e.Index == 1) //TODO: Your condition to make text bold f = new Font(e.Font, FontStyle.Bold); e.DrawBackground(); e.Graphics.DrawString(((ListBox)(sender)).Items[e.Index].ToString(), f, new SolidBrush(e.ForeColor), e.Bounds); e.DrawFocusRectangle(); } 

您需要将DrawMode设置为OwnerDrawFixed(例如,在设计器中)。

使所选项目变为粗体

 public partial class Form1 : Form { public Form1() { InitializeComponent(); ListBox1.Items.AddRange(new Object[] { "me", "myself", "bob"}); // set the draw mode to fixed ListBox1.DrawMode = DrawMode.OwnerDrawFixed; } private void ListBox1_DrawItem(object sender, DrawItemEventArgs e) { // draw the background e.DrawBackground(); // get the font Font font = new Font(e.Font, (e.State & DrawItemState.Selected) == DrawItemState.Selected ? FontStyle.Bold : FontStyle.Regular); // draw the text e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), font, new SolidBrush(ListBox1.ForeColor), e.Bounds); e.DrawFocusRectangle(); } }