【问题标题】:Add listbox items with different colors using a checkbox C#使用复选框 C# 添加具有不同颜色的列表框项
【发布时间】:2017-10-31 14:31:48
【问题描述】:

我正在通过文本框向列表框添加项目,我想知道在选中复选框时如何更改从文本框中添加的列表框项目的颜色。因此,当我选中复选框时,文本框中的颜色变为红色,当我单击按钮将文本框发送到列表框时,列表框项变为红色。如果我不选中复选框,则文本颜色为黑色,因此如果添加的第一个是红色的,那么我添加到黑色的,然后在列表框中我需要看到一个红色和一个黑色。

谢谢,

private void addEventButton_Click(object sender, EventArgs e)
    {


        // Adds events to listbox. 
       if (this.titleTextBox.Text != "")
        {
            listBox1.Items.Add(this.titleTextBox.Text); 
            listBox2.Items.Add(this.titleTextBox.Text);
            this.titleTextBox.Focus();
            this.titleTextBox.Clear();

【问题讨论】:

  • 如果有帮助,请参阅this 回答。

标签: c# colors listbox


【解决方案1】:

处理ListBox的DrawItem事件

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   var someObj = listBox1.Items[e.Index] as MyClass;
   Color backColor = Color.Green;
   if (someObj.ID == someID) {
      backColor = Color.Gray;
   }

   // draw back color and text 
   var g = e.Graphics;

   //background:
   SolidBrush backgroundBrush = new SolidColorBrush(backcolor);
   g.FillRectangle(backgroundBrush, e.Bounds);

   //text:
   SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush;
   g.DrawString(text, e.Font, foregroundBrush, lbReports.GetItemRectangle(index).Location);
}

【讨论】:

  • 但这只有在我点击列表框中的事件时才有效,而不是当我正确添加它时?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 2023-04-05
  • 1970-01-01
  • 2020-10-20
  • 2012-02-09
  • 2020-01-14
相关资源
最近更新 更多