gpt4 book ai didi

c# - ListBox 插入颜色项目

转载 作者:太空狗 更新时间:2023-10-30 00:05:38 25 4
gpt4 key购买 nike

我使用 ListBox 来插入文本,例如 You add Michael in your database, You delete Michael, ...

 listBox1.Items.Insert(0,"You add " + name + " in your database\n");

它工作正常。我如何设置颜色一次为黑色(用于插入)一次为红色(用于删除)?我试过这个:

 public class MyListBoxItem
{
public MyListBoxItem(Color c, string m)
{
ItemColor = c;
Message = m;
}
public Color ItemColor { get; set; }
public string Message { get; set; }
}

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem

if (item != null)
{
e.Graphics.DrawString( // Draw the appropriate text in the ListBox
item.Message, // The message linked to the item
listBox1.Font, // Take the font from the listbox
new SolidBrush(item.ItemColor), // Set the color
0, // X pixel coordinate
e.Index * listBox1.ItemHeight // Y pixel coordinate. Multiply the index by the ItemHeight defined in the listbox.
);
}
else
{
// The item isn't a MyListBoxItem, do something about it
}
}

在插入时:

 listBox1.Items.Insert(0, new MyListBoxItem(Color.Black, "You add " + name + " in your database\n"));
listBox1.Items.Insert(0, new MyListBoxItem(Color.Red, "You delete " + name + "\n"));

此代码有效,但当我插入多个项目时,scrol 无法正常工作 - 文本不会出现。我究竟做错了什么?或者还有其他方法吗?

最佳答案

您是否考虑过在报 TableView 中使用 ListView 而不是列表框?这样您就不必为了获得颜色而自定义绘图。

关于c# - ListBox 插入颜色项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9803064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com