.NET中DataGridView 控件可以每个数据行显示不同的背景颜色,方便用户查看,而ListBox却没有实现这样的显示,这篇文章我们就要介绍怎样让ListBox实现隔行显示交替的背景色。
要实现ListBox隔行显示不同的背景色并不是很难,下面我们就一步步的来实现:
1、 继承 ListBox,设置其DrawMode 为 OwnerDrawFixed,看下代码:
public ListBoxEx()
: base()
{
base.DrawMode = DrawMode.OwnerDrawFixed;
}
2、 给继承的控件添加3个属性:RowBackColor1,RowBackColor2,SelectedColor,这三个颜色分别是数据项的交替的背景色和数据项选择后的背景色。
3、 重写控件的OnDrawItem函数,当数据项的索引为奇数时,用RowBackColor1绘制背景,为偶数时用 RowBackColor2绘制背景,数据项当选中时,用SelectedColor绘制背景,然后绘制项的文本,如果有焦点的话就绘制聚焦框。看看具体代码:
protected override void OnDrawItem(DrawItemEventArgs e)
{
base.OnDrawItem(e);
if (e.Index != -1)
{
if ((e.State & DrawItemState.Selected)
== DrawItemState.Selected)
{
RenderBackgroundInternal(
e.Graphics,
e.Bounds,
_selectedColor,
_selectedColor,
Color.FromArgb(200, 255, 255, 255),
true,
LinearGradientMode.Vertical);
}
else
{
Color backColor;
if (e.Index % 2 == 0)
{
backColor = _rowBackColor2;
}
else
{
backColor = _rowBackColor1;
}
using (SolidBrush brush = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(brush, e.Bounds);
}
}
string text = Items[e.Index].ToString();
TextFormatFlags formatFlags = TextFormatFlags.VerticalCenter;
if (RightToLeft == RightToLeft.Yes)
{
formatFlags |= TextFormatFlags.RightToLeft;
}
else
{
formatFlags |= TextFormatFlags.Left;
}
TextRenderer.DrawText(
e.Graphics,
text,
Font,
e.Bounds,
ForeColor,
formatFlags);
if ((e.State & DrawItemState.Focus) ==
DrawItemState.Focus)
{
e.DrawFocusRectangle();
}
}
}