我尝试了这段代码,但它不起作用:
private void LoadKeys(Dictionary<string,List<string>> dictionary, string FileName)
{
string line = System.String.Empty;
using (StreamReader sr = new StreamReader(keywords))
{
while ((line = sr.ReadLine()) != null)
{
string[] tokens = line.Split(',');
dictionary.Add(tokens[0], tokens.Skip(1).ToList());
listBox1.Items.Add(new MyListBoxItem(Color.Green, "Url: " + tokens[0] + " --- " + "Localy KeyWord: " + tokens[1]));
}
}
}
现在类 MyListBoxItem:
public class MyListBoxItem
{
public MyListBoxItem(Color c, string m)
{
ItemColor = c; Message = m;
}
public Color ItemColor
{
get;
set;
}
public string Message
{
get;
set;
}
}
和 listBox1_DrawItem 事件:
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
}
}
在尝试使用颜色和绘制项目之前的 ListBox 中,我使用了这一行:
listBox1.Items.Add("Url: " + tokens[0] + " --- " + "Localy KeyWord: " + tokens[1]);
结果例如: Url: http://www.google.com --- Localy KeyWord: google
现在,当尝试将这条线用绿色着色时,颜色仍然是黑色,而 listBox 中的文本现在是:
GatherLinks.Form1+MyListBoxItem 奇怪。
我想要做的是在listBox的第一行中着色Url:红色---蓝色和localykeyword:黄色第二行Url:绿色---红色和值例如蓝色的谷歌。
我该怎么做 ?