拾色器组合框 [英] Color Picker Combo Box

查看:71
本文介绍了拾色器组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要自定义组合框的每个项目,与字体,背景等相同。


是否有简单的方法来设置每个组合框项目的自定义背景颜色?

I want to customize my combobox each item, same as font, background, etc.
Is there any simple way to set custom background color of each Combobox item?

推荐答案

这是简单的示例。在此示例中,我的组合框有一些与颜色名称相同的项目(红色,蓝色等),并由此更改了每个项目的背景。只需执行以下步骤:




1)将 DrawMode 设置为 OwnerDrawVariable

This is simple example to do that. In this example my combobox has some item same as color name (Red, Blue, etc) and change the background of each item from this. Just flow the steps:

1) Set the DrawMode to OwnerDrawVariable:

如果此属性设置为 Normal ,则此控件将永远不会引发DrawItem事件

If this property set to Normal this control never raise DrawItem event

ComboBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;



2)添加 DrawItem 事件:


2) Add an DrawItem event:

ComboBox1.DrawItem += new DrawItemEventHandler(ComboBox1_DrawItem);



3)输入您自己的代码来自定义每个项目:


3) Entry your own code to customize each item:

private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   Graphics g = e.Graphics;
   Rectangle rect = e.Bounds; //Rectangle of item
   if (e.Index >= 0)
   {
      //Get item color name
      string itemName = ((ComboBox)sender).Items[e.Index].ToString();

      //Get instance a font to draw item name with this style
      Font itemFont = new Font("Arial", 9, FontStyle.Regular);

      //Get instance color from item name
      Color itemColor = Color.FromName(itemName);

      //Get instance brush with Solid style to draw background
      Brush brush = new SolidBrush(itemColor);

      //Draw the item name
      g.DrawString(itemName, itemFont, Brushes.Black, rect.X, rect.Top);

      //Draw the background with my brush style and rectangle of item
      g.FillRectangle(brush, rect.X, rect.Y, rect.Width, rect.Height);
   }
}

4)还需要添加颜色:

4) Colors need to be added as well:

ComboBox1.Items.Add("Black");
ComboBox1.Items.Add("Blue");
ComboBox1.Items.Add("Lime");
ComboBox1.Items.Add("Cyan");
ComboBox1.Items.Add("Red");
ComboBox1.Items.Add("Fuchsia");
ComboBox1.Items.Add("Yellow");
ComboBox1.Items.Add("White");
ComboBox1.Items.Add("Navy");
ComboBox1.Items.Add("Green");
ComboBox1.Items.Add("Teal");
ComboBox1.Items.Add("Maroon");
ComboBox1.Items.Add("Purple");
ComboBox1.Items.Add("Olive");
ComboBox1.Items.Add("Gray");

您可以根据需要更改矩形大小和位置以绘制自己的项目。


我希望这篇文章有用。

You can change the rectangle size and position to draw your own item as you want.
I hope this post is useful.

这篇关于拾色器组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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