您的位置:首页 > 编程语言 > C#

C# WinForm控件美化扩展系列之ListBox

2011-03-21 14:05 1086 查看
.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),

0.45f,

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();

}

}
}

转载:http://www.csharpwin.com/csharpresource/584.shtml
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: