构建颜色选择器控件





5.00/5 (1投票)
本文将向您展示如何创建一个颜色选择器控件,其外观将类似于右侧的图像。 首先要说明的是
本文将向您展示如何创建一个颜色选择器控件,其外观将类似于右侧的图像。
首先要说明的是填充颜色的方式。我们可以手动填充可用的颜色,或者我们可以找到一种使用 .NET 获取所有已知颜色的方法。
我们将使用 System.Drawing.KnownColor
枚举类型的数值来填充颜色列表。 这可以使用 Enum.GetValues
方法完成
System.Drawing.KnownColor[] colors =
(System.Drawing.KnownColor[])System.Enum.GetValues(typeof(System.Drawing.KnownColor));
为了更好的可用性,所有代码逻辑都可以放置在一个 用户控件 中,以便您可以在项目的许多地方使用它。
用户控件代码
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="Select color" Value="-1"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="DropDownList1"
runat="server" ErrorMessage="
Select a color from the list !" InitialValue="-1">
</asp:RequiredFieldValidator>
public partial class ColorsPicker : System.Web.UI.UserControl
{
public System.Drawing.Color SelectedColor
{
get {
if (DropDownList1.SelectedIndex > 0)
{
//get the selected color
string SelectedColorStr = DropDownList1.SelectedValue;
//' conver the color string to System.drawing.color object
System.Drawing.ColorConverter converter = new System.Drawing.ColorConverter();
System.Drawing.Color objColor =
(System.Drawing.Color)converter.ConvertFromString(SelectedColorStr);
return objColor;
}
// if there is no color selected
// we return empty color object
else
{
return new System.Drawing.Color();
}
}
set {
string Color = value.Name;
ListItem li = DropDownList1.Items.FindByValue(Color);
// if found in the colors list , we select the matched color
if (li != null)
{
DropDownList1.ClearSelection();
li.Selected = true;
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
BindFillColorslist();
//set the Background color of the listitem to the same color which the item represents
SetCbackColorsForListItems();
}
private void SetCbackColorsForListItems()
{
foreach (ListItem li in DropDownList1.Items)
{
li.Attributes["style"] = " background-color: " + li.Value;
}
}
// this function will fill the dropdownlist with the known colors
private void BindFillColorslist()
{
// get the list of known colors
System.Drawing.KnownColor[] colors =
(System.Drawing.KnownColor[])System.Enum.GetValues(typeof(System.Drawing.KnownColor));
//' add them to the drodownlist
foreach (System.Drawing.KnownColor c in colors)
{
DropDownList1.Items.Add(c.ToString());
}
}
}
关于用户控件代码的一些重要说明
- 可以使用 SelectedColor 属性来设置/获取颜色列表中选定的颜色,此属性接受类型为 System.Drawing.Color 的对象。
- SetCbackColorsForListItems 函数负责根据项目所代表的颜色为每个项目设置背景颜色。
- BindFillColorslist 用于填充颜色列表。
这是一个在您的页面中使用控件的示例
<uc1:ColorsPicker ID="ColorsPicker1" runat="server" />
<asp:Button ID="Button2" runat="server" Text="show color" OnClick="Button2_Click" />
<asp:Label ID="lblColor" runat="server">Color Test</asp:Label></div>
protected void Button2_Click(object sender, EventArgs e)
{ // set the label back color based on the selected date from the list
lblColor.BackColor = ColorsPicker1.SelectedColor;
}
现在,当您单击按钮时,标签的背景颜色将根据颜色列表中选择的颜色进行设置。