【问题标题】:How to Color particular item of combobox如何为组合框的特定项目着色
【发布时间】:2014-07-04 08:00:12
【问题描述】:

我想为组合框中的所有 “不可选择” 文本着色。我怎样才能做到这一点?我试过了,但我无法做到这一点。

我的代码如下:

private class ComboBoxItem
{
    public int Value { get; set; }
    public string Text { get; set; }
    public bool Selectable { get; set; }
}

private void Form1_Load(object sender, EventArgs e)
{
    this.comboBox1.ValueMember = "Value";
    this.comboBox1.DisplayMember = "Text";
    this.comboBox1.Items.AddRange(new[] {
        new ComboBoxItem() { Selectable = true, Text="Selectable0", Value=0,  },
        new ComboBoxItem() { Selectable = true, Text="Selectable1", Value=1},
        new ComboBoxItem() { Selectable = true, Text="Selectable2", Value=2},
        new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=3},
        new ComboBoxItem() { Selectable = true, Text="Selectable3", Value=4},
        new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=5},
    });

    this.comboBox1.SelectedIndexChanged += (cbSender, cbe) =>
    {
        var cb = cbSender as ComboBox;

        if (cb.SelectedItem != null && cb.SelectedItem is ComboBoxItem && ((ComboBoxItem)cb.SelectedItem).Selectable == false)
        {
            // deselect item
            cb.SelectedIndex = -1;
        }
    };
}

我正在使用 C#.NET。

【问题讨论】:

  • I tried it but ,不,你没有。在您的代码中没有任何地方可以更改项目的颜色。您所做的只是在选择不可选择的项目时将选定的索引设置为 -1(无项目)。
  • 嗯,我猜他希望有一些自动的东西。您在哪里更改 Text 或 bool Selectable 属性?这将是寻找的地方,如果它应该动态工作..
  • 您的问题解决了吗?

标签: c# .net winforms combobox


【解决方案1】:

您需要将 ComboBoxItem 上的前景属性设置为您需要的颜色。

new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=3, Foreground = Brushes.Red},

MSDN page

【讨论】:

  • 尽管名称为 ComboBoxItem,但这是 Winforms,并且他的自定义类没有 WPF 的 ComboBoxItem 的任何功能。
【解决方案2】:

您需要将ComboBox.DrawMode 设置为OwnerDrawxxx 并编写DrawItem 事件的脚本,例如像这样:

 private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
 {

    e.DrawBackground();
     // skip without valid index
    if (e.Index >= 0) 
    {
      ComboBoxItem cbi = (ComboBoxItem)comboBox1.Items[e.Index];
      Graphics g = e.Graphics;
      Brush brush =  new SolidBrush(e.BackColor);
      Brush tBrush = new SolidBrush(cbi.Text == "Unselectable" ? Color.Red : e.ForeColor);

      g.FillRectangle(brush, e.Bounds);
      e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), e.Font,
                 tBrush, e.Bounds, StringFormat.GenericDefault);
      brush.Dispose();
      tBrush.Dispose();
    }
    e.DrawFocusRectangle();

 }

这部分cbi.Text == "Unselectable"显然不好。由于您已经拥有一个属性Selectable,因此它应该真的是!cbi.Selectable"。当然,您必须确保该属性与文本同步。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    相关资源
    最近更新 更多