【问题标题】:C# How to change the color of Combobox items? [closed]C#如何改变组合框项目的颜色? [关闭]
【发布时间】:2013-09-01 19:52:03
【问题描述】:

winform 上的组合框, 组合框填充数据表三列(id,name,status)

combobox.displaymember = "name";
combobox.valuemember = "id";

我想更改状态栏

的组合框项目的颜色

请指教。

【问题讨论】:

  • 有人在winforms(状态栏)中听说过这件事吗?我只在 WPF 中知道这个术语!?
  • 数据表中的状态列名
  • 看这里,stackoverflow.com/questions/4667532/… 如果你想对颜色做出决定,你必须在静态位置获得状态或从回调中的某处检索它们
  • 非常模糊,但也许我的答案是正确的?

标签: c# winforms colors combobox


【解决方案1】:

我能够做到这一点,但有一个错误。 第一步。

  1. 在表单中添加组合框 (comboBox1)
  2. 将comboBox1 的DrawItem 事件更改为comboBox1_DrawItem(我们的方法如下)
  3. 编辑:将 comboBox1 的 Draw Mode 属性更改为 OwnerDrawFixedOwnerDrawVariable
  4. 实现comboBox1_DrawItem。请注意,我在ComboBoxValue.Status 上切换了画笔

    private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
    {  
        Brush brush;
        var g = e.Graphics;
        var rect = e.Bounds;
        var n = "";
        var f = new Font("Arial", 9, FontStyle.Regular);
    
        switch (((ComboBoxValue)((ComboBox)sender).SelectedItem).Status)
        {
            case "one":
                brush = Brushes.Red;
                break;
            case "two":
                brush = Brushes.Green;
                break;
            default:
                brush = Brushes.White;
                break;
        }
        if (e.Index >= 0)
        {
            n = ((ComboBoxValue)((ComboBox)sender).SelectedItem).Name;
        }
        g.FillRectangle(brush, rect.X, rect.Y,rect.Width, rect.Height);
        g.DrawString(n, f, Brushes.Black, rect.X, rect.Y);
    }
    
  5. 我使用我自己的类的 IList 作为数据源。你的会不一样。

    public class ComboBoxValues : System.Collections.ObjectModel.Collection<ComboBoxValue>
    {
        public ComboBoxValues()
        {
            this.Add(new ComboBoxValue
            {
                Name = "chad",
                Id = 123,
                Status = "one"
            });
            this.Add(new ComboBoxValue
            {
                Name = "different chad",
                Id = 123,
                Status = "two"
            });
        }
    }
    public class ComboBoxValue
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public string Status { get; set; }
    }
    
  6. 设置您的DataSource

    comboBox1.DataSource = new ComboBoxValues();
    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "Id";
    

您很快就会看到的错误是,由于某种原因,颜色似乎只有在您将鼠标悬停在它们上方时才会发生变化。在我回到这个问题之前,也许其他人会意识到这个错误。祝你好运!

【讨论】:

  • 你发现鼠标悬停的bug了吗?
  • @Prix,因为这几乎是 3 年前的事了,我不记得为什么我没有发布该错误的修复程序。然而,回顾过去,我确信这只是一个刷新问题。切换后尝试在控件上调用刷新。
  • 感谢您的输入,我使用定制的组合框解决了这个问题,也提出了一个关于它的问题,因为它把我困在了其他地方,但也找到了答案并发布了它;)。由于某种原因,覆盖 OnDraw 不会产生与您在此处遇到的相同问题。
猜你喜欢
  • 1970-01-01
  • 2011-10-17
  • 2013-12-18
  • 2017-12-13
  • 1970-01-01
  • 1970-01-01
  • 2016-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多