摘要: 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方法,添加代码:
foreach ( string 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 #region ItemColor public class ItemColor { private Color m_ForeColor; private Color m_BackColor; public Color ForeColor { get { return m_ForeColor; } set { m_ForeColor = value; } }#endregion
BackColor #region BackColor public Color BackColor { get { return m_BackColor; } set { m_BackColor = value; } } public ItemColor() { SetDefault(); } public void SetDefault() { m_ForeColor = Color.Empty; m_BackColor = Color.Empty; } }#endregion 为了和ListBox的Item集合的访问方法相似,我们在做了一个ItemColorCollection类:
ItemColorCollection #region ItemColorCollection public class ItemColorCollection { private ArrayList m_Items; private int m_Count; public Color ForeColor; public Color BackColor; public int Count { set { m_Count = value; } } public ItemColorCollection() { m_Items = new ArrayList(); m_Count = 0 ; } public ItemColor this [ int iIndex] { get { /**/ /* if ( iIndex > m_Count-1 ) { throw new ArgumentOutOfRangeException("Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: iIndex"); } */ if ( iIndex > m_Items.Count - 1 ) { for ( int i = m_Items.Count ; i <= iIndex ; ++ i ) { m_Items.Add( null ); } ItemColor ic = new ItemColor(); m_Items[iIndex] = ic; return ic; } else { if ( m_Items[iIndex] == null ) { ItemColor ic = new ItemColor(); m_Items[iIndex] = ic; return ic; } else { return (ItemColor)m_Items[iIndex]; } } } } }#endregion 有了这两个辅助类后,我们在写我们的ColorfulListBox,代码如下:
ColorfulListBox #region ColorfulListBox using System; using System.IO; using System.Text; using System.Drawing; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; using System.Collections; namespace CustomizeControls { /**/ /// <summary> /// Summary description for ColorfulListBox. /// </summary> [DefaultProperty( " Text " ), ToolboxData( " <{0}:ColorfulListBox runat="server"></{0}:ColorfulListBox> " )] public class ColorfulListBox : System.Web.UI.WebControls.ListBox { private ItemColorCollection m_ItemsColor; public ColorfulListBox() { m_ItemsColor = new ItemColorCollection(); } public ItemColorCollection ItemsColor { get { m_ItemsColor.Count = this .Items.Count; return m_ItemsColor; } } /**/ /// <summary> /// Render this control to the output parameter specified. /// </summary> /// <param name="output"> The HTML writer to write out to </param> protected override void Render(HtmlTextWriter output) { this .RenderBeginTag(output); StringBuilder strbStyle = new StringBuilder(); for ( int i = 0 ; i < this .Items.Count ; ++ i ) { ListItem li = this .Items[i]; output.Write( " <option value=" " + li.Value + " " " ); if ( this .SelectedIndex == i ) { output.Write( " selected="selected" " ); } /**/ /* foreach( string 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); } */ if ( m_ItemsColor[i] != null ) { Color cForeColor = m_ItemsColor[i].ForeColor; if ( cForeColor != Color.Empty ) { strbStyle.Append(String.Format( " color:{0}; " , cForeColor.Name)); } Color cBackColor = m_ItemsColor[i].BackColor; if ( cBackColor != Color.Empty ) { strbStyle.Append(String.Format( " background-color:{0} " , cBackColor.Name)); } if ( strbStyle.Length > 0 ) { strbStyle.Insert( 0 , " style=" " ); strbStyle.Append( " " " ); output.Write(strbStyle.ToString()); strbStyle.Remove( 0 , strbStyle.Length); } } output.Write(" > " + li.Text + " </option> " ); } this .RenderEndTag(output); } } }#endregion 编译好我们的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: <Not Set> AliceBlue AntiqueWhite Aqua Aquamarine Azure Beige Bisque Black BlanchedAlmond Blue BlueViolet Brown BurlyWood CadetBlue Chartreuse Chocolate Coral CornflowerBlue Cornsilk Crimson Cyan DarkBlue DarkCyan DarkGoldenrod DarkGray DarkGreen DarkKhaki DarkMagenta DarkOliveGreen DarkOrange DarkOrchid DarkRed DarkSalmon DarkSeaGreen DarkSlateBlue DarkSlateGray DarkTurquoise DarkViolet DeepPink DeepSkyBlue DimGray DodgerBlue Firebrick FloralWhite ForestGreen Fuchsia Gainsboro GhostWhite Gold Goldenrod Gray Green GreenYellow Honeydew HotPink IndianRed Indigo Ivory Khaki Lavender LavenderBlush LawnGreen LemonChiffon LightBlue LightCoral LightCyan LightGray LightGoldenrodYellow LightGreen LightPink LightSalmon LightSeaGreen LightSkyBlue LightSlateGray LightSteelBlue LightYellow Lime LimeGreen Linen Magenta Maroon MediumAquamarine MediumBlue MediumOrchid MediumPurple MediumSeaGreen MediumSlateBlue MediumSpringGreen MediumTurquoise MediumVioletRed MidnightBlue MintCream MistyRose Moccasin NavajoWhite Navy OldLace Olive OliveDrab Orange OrangeRed Orchid PaleGoldenrod PaleGreen PaleTurquoise PaleVioletRed PapayaWhip PeachPuff Peru Pink Plum PowderBlue Purple Red RosyBrown RoyalBlue SaddleBrown Salmon SandyBrown SeaGreen SeaShell Sienna Silver SkyBlue SlateBlue SlateGray Snow SpringGreen SteelBlue Tan Teal Thistle Tomato Transparent Turquoise Violet Wheat White WhiteSmoke Yellow YellowGreen That's all.