如何设置列表框项目备用背景色 [英] how to set listbox items alternate backcolor

查看:75
本文介绍了如何设置列表框项目备用背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows应用程序上使用列表框控件,我想在列表框项目上设置备用背景色,我已经尝试过...

i m using a listbox control on my windows application , i want to set a alternate backcolor on listbox items , i have tried...

private void listBox2_DrawItem(object sender, DrawItemEventArgs e)
       {
           //bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);


           int index = e.Index;
           if (index >= 0 && index < listBox2.Items.Count)
           {

               Graphics g = e.Graphics;
               Color color;


                   if (index % 2 == 0)
                   {
                       color = Color.Gray;
                   }
                   else
                   {
                       color = Color.White;
                   }

               /* Draw Background */
               g.FillRectangle(new SolidBrush(color), e.Bounds);

               /* Draw Item Text */
               g.DrawString(listBox2.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds, StringFormat.GenericDefault);

           }
           e.DrawFocusRectangle();
       }



而且我认为使用此代码对列表框没有影响:
我还缺少什么...



and i see no effect on listbox with this code:
what else i m missing...

推荐答案

尝试一下:
Try this:
private static void recolorListItems(ListView lv) {
        for (int i = 0; i < lv.Items.Count; ++i)
         {
            var item = lv.Items[i];
            item.BackColor = (i % 2 == 0) ? Color.Gray : Color.White;
        }
    }


这篇关于如何设置列表框项目备用背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆