c# - 使用复选框 C# 添加具有不同颜色的列表框项目

标签 c# colors listbox

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

谢谢,

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();

最佳答案

处理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);
}

关于c# - 使用复选框 C# 添加具有不同颜色的列表框项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44273706/

相关文章:

c# - 无法在 WPF 中设置 DialogResult

excel - 更改图表上系列的填充颜色

ios - iPhone 不显示准确的颜色

c# - 使用 DataTemplate 在 WPF 中通过 LINQ to SQL 绑定(bind) ListBox 的 ListItem 属性的两种方式

google-chrome - listbox.js 或 pickers.js 未从 sv-se 加载,错误 404

c# - Visual Studio 2012-s 自定义项目模板不可见

c# - 如何在 ASP.NET Core 2.1 出现第一个错误后停止验证

c# - 脚本错误 : Not authorized to send Apple events to Terminal when running code on Visual Studio 2017 for Mac

c# - 树节点文本不同颜色的词

c# - 如何将 Find 方法与通用 List 类一起使用以按名称查找特定实例