文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C# WinForm控件美化扩展系列之ListBox

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

时间:2011-03-21  来源:誓言的爱

.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

相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载