Colorful ListBox Control

摘要:
    Asp.net控件中给我们提供了一个ListBox,我们可以通过它在Html文档中产生一个<select></select>Tag,用来选取预先设定的条目(ListItem)。ListBox除了继承来自WebControl之外的成员和属性外,他主要提供了对ListItem集合的包含,由此我们可以获得一个或一组Text、Value和Seleted值。

问题:
    这个系统提供的ListBox控件在操做和功能上能满足我们的需要,因为他本来就是用<select>呈现的,他要实现的东东必然受它限制。但是在外观呈现上,ListBox确实实现的不太令人满意,ListBox给我们提供了ForeColor和BackColor,但是设置这两个属性,整个ListBox的所有选项都变成了同样的ForeColor和BackColor。而ListBox里的ListItem又没有提供ForeColor和BackColor,我曾经试过这样:

    ListItem.Attributes.CssStyle.Add(“color”, “yellow”);
    ListItem.Attributes.CssStyle.Add(“background
-color”,“blue”);

但是结果没有效果

正文:
    所以我们自己实现一个ColorfulListBox,这里有两个方案,我们可以使用前面提到的代码,我们给ListItem添加的CssStyle虽然没有被呈现,但是确实是被加入了的,只是系统带的ListBox在呈现时候把他们忽略了。我们最简单的办法就是继承ListBox,重载Render方法,添加代码:

    foreachstring strKey in li.Attributes.CssStyle.Keys )
    
{
     strbStyle.Append(String.Format(
"{0}:{1};", strKey,
      li.Attributes.CssStyle[strKey]));
    }

    
if ( strbStyle.Length > 0 )
    
{
     strbStyle.Insert(
0" style="");
     strbStyle.Append(
""");
     output.Write(strbStyle.ToString());
     strbStyle.Remove(
0, strbStyle.Length);
    }

    这样就把ListItem里的CSS手动提取出来了,问题虽然说解决了,可是用起来太麻烦,还要去取一大堆CSS属性,不方便使用,例如我要做第三Item红字的ListBox,我就需要:

    ColorfulListBox lstb = ColorfulListBox();
    
// add items
    
// 
    lstb.Items[2].Attributes.CssStyle[”color”] = “red”;

为了方便使用,我们就再多做一点工作,接下来我们给ListBox添加一个Items颜色列表:

ItemColor

BackColor

    为了和ListBox的Item集合的访问方法相似,我们在做了一个ItemColorCollection类:

ItemColorCollection

    有了这两个辅助类后,我们在写我们的ColorfulListBox,代码如下:

ColorfulListBox

    编译好我们的ColorfulListBox后,其他项目中引用ColorfulListBox.dll,就可以在工具箱中拖出ColorfulListBox,我们可以这样给一个ListBox设置每个Item的颜色了:

   clstb.ItemsColor[3].ForeColor = Color.Red;
   clstb.ItemsColor[
2].BackColor = Color.Yellow;
   clstb.ItemsColor[
2].ForeColor = Color.Black;
   clstb.ItemsColor[
1].ForeColor = Color.Blue;

ColorfulListBox效果示例:

Color: 
 

That's all.

posted on 2004-03-24 15:25  birdshome  阅读(6241)  评论(9编辑  收藏  举报

导航