65.9K
CodeProject 正在变化。 阅读更多。
Home

C# ColorListBox

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.40/5 (21投票s)

2002年5月30日

viewsIcon

151491

downloadIcon

3221

在本文中,我们将看到如何编写一个所有者绘制的 ListBox

Sample Image - ColorListBox.gif

引言

在本文中,我们将学习如何编写所有者绘制的 ListBox 控件。通常,Windows 会处理绘制 ListBox 中显示的项目的任务。您可以使用 DrawMode 属性并处理 MeasureItemDrawItem 事件,以提供覆盖 Windows 提供的自动绘制并自行绘制项目的功能。您可以使用所有者绘制的 ListBox 控件来显示可变高度的项目、图像,或者列表中文本的颜色或字体不同。

描述

我们首先创建一个 Windows 应用程序。将 ListBox 添加到窗体并将它的 DrawMode 属性设置为 OwnerDrawVariable。或者,您可以将以下行添加到窗体的 InitializeComponent 函数中:

//lstColor is ListBox control
this.lstColor.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;

接下来,在以上行下方添加以下行:

//tell windows we are interested in drawing items in ListBox on our own
this.lstColor.DrawItem += new DrawItemEventHandler(this.DrawItemHandler);

//tell windows we are interested in providing  item size
this.lstColor.MeasureItem += 
  new System.Windows.Forms.MeasureItemEventHandler(this.MeasureItemHandler);

通过这样做,Windows 将向我们发送 DrawItemMeasureItem 事件,用于添加到 ListBox 的每个项目。

接下来,为这些事件添加处理程序:

private void DrawItemHandler(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    e.DrawFocusRectangle();
    e.Graphics.DrawString(data[e.Index], 
                          new Font(FontFamily.GenericSansSerif, 
                                   14, FontStyle.Bold),
                          new SolidBrush(color[e.Index]), 
                          e.Bounds);
 
}

private void MeasureItemHandler(object sender, MeasureItemEventArgs e)
{
    e.ItemHeight= 22;
}

在上面的代码中,date 是一个保存要插入的项目的数组,color 是 Color 类的数组。

完成了!

请将您的评论发送至 lparam@hotmail.com

© . All rights reserved.