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