![](/img/trans.png)
[英]How can i color the text of a specific item in a specific case in listBox?
[英]How do i color a specific text in a specific item/s in a ListBox?
我嘗試了此代碼,但無法正常工作:
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]);
結果例如:網址: http : //www.google.com --- Localy關鍵字:google
現在,當嘗試為其着色時,綠色的這一行仍然是黑色,並且listBox中的文本現在是:
GatherLinks.Form1 + MyListBoxItem很奇怪。
我想要做的是在列表框的第一行中為Url着色:紅色為紅色---在藍色和localykeyword:在黃色中第二行Url:在綠色為紅色---在紅色和值例如Google in Blue。
我該怎么做 ?
您是否更改了列表框的DrawMode屬性以允許所有者繪圖?
listBox1.DrawMode = DrawMode.OwnerDrawFixed;
我正在我的一個項目中這樣做。 根據上面的交鑰匙,我的行:
tasksListBox.DrawMode = DrawMode.OwnerDrawFixed;
tasksListBox.DrawItem += listBox_DrawItem;
在我的表單的初始化代碼中。 DrawItem的代碼處理選擇顏色之類的問題
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index == -1)
{
return;
}
e.DrawBackground();
Graphics g = e.Graphics;
var selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;
var lb = (ListBox)sender;
if (selected)
{
g.FillRectangle(new SolidBrush(Color.DarkBlue), e.Bounds);
g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.White), new PointF(e.Bounds.X, e.Bounds.Y));
return;
}
var item = (ProjectToDoRecord)lb.Items[e.Index];
var textColor = item.TrafficLight();
g.FillRectangle(new SolidBrush(Color.White), e.Bounds);
g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(textColor), new PointF(e.Bounds.X, e.Bounds.Y));
}
繪制的每個項目的顏色由textColor確定。 設置為正在繪制的項目中定義的顏色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.