在 ComboBox 中显示颜色列表 - 颜色选择器 [英] Show list of colors in ComboBox - Color Picker

查看:35
本文介绍了在 ComboBox 中显示颜色列表 - 颜色选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

] 想用所有颜色的列表填充我的 ComboBox.我期待这样的事情:

]'d like to fill my ComboBox with a list of all colors. I was expecting Something like:

CBcolor.DataSource = AllColor;

然后我想像这样使用我的 ComboBox:

Then I'd like to use my ComboBox like this:

Color selected = CBcolor.selectedvalue;   
C_ObjetGraphique cercle = new dessin.Cercle(e.Location, selected, selected, 100);
cercle.Affiche();
ledessin.ajoute(cercle);

如何在我的 ComboBox 中显示颜色列表作为颜色选择器?

How can I Show list of colors in my ComboBox as a color picker?

推荐答案

一般情况下需要设置颜色列表作为组合框的数据源.您可能有一些预定义颜色的列表,例如 Color.Red、Color.Green、Color.Blue;你可以依赖KnownColor,或者你可以使用反射来获取Color类型的Color属性.

In general you need to set the list of colors as data source of combo box. You may have a list of some predefined colors like Color.Red, Color.Green, Color.Blue; You may rely on KnownColor, or you may use reflection to get Color properties of Color type.

在这个例子中,我使用 Color 类型的颜色属性来显示一个像这样的组合框:

In this example I use color properties of the Color type to show a combo box like this:

获取组合框的颜色列表和设置数据源:

Get list of colors and set data source of combo box:

comboBox1.DataSource = typeof(Color).GetProperties()
    .Where(x => x.PropertyType == typeof(Color))
    .Select(x => x.GetValue(null)).ToList();

处理组合框的自定义绘制:

Handle custom draw of the combo box:

comboBox1.MaxDropDownItems = 10;
comboBox1.IntegralHeight = false;
comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.DrawItem += comboBox1_DrawItem;

然后对于 comboBox1_DrawItem:

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    if (e.Index >= 0)
    {
        var txt = comboBox1.GetItemText(comboBox1.Items[e.Index]);
        var color = (Color)comboBox1.Items[e.Index];
        var r1 = new Rectangle(e.Bounds.Left + 1, e.Bounds.Top + 1,
            2 * (e.Bounds.Height - 2), e.Bounds.Height - 2);
        var r2 = Rectangle.FromLTRB(r1.Right + 2, e.Bounds.Top,
            e.Bounds.Right, e.Bounds.Bottom);
        using (var b = new SolidBrush(color))
            e.Graphics.FillRectangle(b, r1);
        e.Graphics.DrawRectangle(Pens.Black, r1);
        TextRenderer.DrawText(e.Graphics, txt, comboBox1.Font, r2,
            comboBox1.ForeColor, TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
    }
}

从组合框中获取选定的颜色:

Get the selected color from combo box:

if(comboBox1.SelectedIndex>=0)
    this.BackColor = (Color)comboBox1.SelectedValue;

这篇关于在 ComboBox 中显示颜色列表 - 颜色选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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