【问题标题】:combo box - drop down list [duplicate]组合框 - 下拉列表 [重复]
【发布时间】:2014-05-13 08:24:49
【问题描述】:

我想知道是否可以创建一个组合框(下拉列表)并在下拉列表中绘制特定的单元格。 所以,如果我在下拉列表中有五个项目,例如第二个项目和最后一个项目将被涂成蓝色,而其他项目将被涂成灰色。 有可能吗?

System.Windows.Forms.ComboBox comboBox;
comboBox = new System.Windows.Forms.ComboBox();
comboBox.AllowDrop = true;
comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
comboBox.FormattingEnabled = true;
comboBox.Items.AddRange(excel.getPlanNames());
comboBox.Location = new System.Drawing.Point(x, y);
comboBox.Name = "comboBox1";
comboBox.Size = new System.Drawing.Size(sizeX, sizeY);
comboBox.TabIndex = 0;
group.Controls.Add(comboBox);

感谢您的帮助..

【问题讨论】:

标签: c# winforms


【解决方案1】:

您可以使用DrawItem 事件。

首先您必须将ComboBoxDrawMode 设置为OwnerDrawFixed

然后您将DrawItem 设置为如下所示:

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    Font font = (sender as ComboBox).Font;
    Brush backgroundColor;
    Brush textColor;

    if (e.Index == 1 || e.Index == 3)
    {
        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        {
            backgroundColor = Brushes.Red;
            textColor = Brushes.Black;
        }
        else
        {
            backgroundColor = Brushes.Green;
            textColor = Brushes.Black;
        }
    }
    else
    {
        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        {
            backgroundColor = SystemBrushes.Highlight;
            textColor = SystemBrushes.HighlightText;
        }
        else
        {
            backgroundColor = SystemBrushes.Window;
            textColor = SystemBrushes.WindowText;
        }
    }
    e.Graphics.FillRectangle(backgroundColor, e.Bounds);
    e.Graphics.DrawString((sender as ComboBox).Items[e.Index].ToString(), font, textColor, e.Bounds);
}

本示例将默认背景颜色设为绿色和黑色文本,并且突出显示的项目将具有红色背景和黑色文本,索引 1 和 3 处的项目。

您还可以使用font 变量设置单个项目的字体。

【讨论】:

  • 救了我.. 非常感谢 :)))
猜你喜欢
  • 2016-02-20
  • 2016-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
相关资源
最近更新 更多