2015年5月29日 星期五
C# ListBox 如何新增ListBox裡面的item項目的背景顏色 或字體顏色
ListBox預設是存放字串, 如果ListBox裡面的item要做到背景色或字型顏色的變化,就 要使用Drawitem事件調適,傳統的方法是不合適的。
//--------產生ListBox
main
{
ListBox SearchListBoxResult = new ListBox();
SearchListBoxResult.Name = "SearchListBoxResult_ListBox";
SearchListBoxResult.Tag = "AriesItemTitle";
SearchListBoxResult.Left = 5;
SearchListBoxResult.Top = 65;
SearchListBoxResult.Width = 200;
SearchListBoxResult.Height = 300;
SearchListBoxResult.Items.Add(new MyListBoxItem(Color.White , "123" ));
SearchListBoxResult.DoubleClick += SearchListBoxResult_Click;
SearchListBoxResult.DrawItem += SearchListBoxResult_DrawItem;
this.tabPage3.Controls.Add(SearchListBoxResult);
SearchListBoxResult.DrawMode = DrawMode.OwnerDrawFixed;//----啟動drawitem事件
}
/// <summary> 製作一個ListBox item項目顏色的增加
/// 製作一個ListBox item項目顏色的增加
/// </summary>
public class MyListBoxItem
{
public MyListBoxItem(Color c, string m)
{
ItemColor = c;//------顏色
Message = m;//------- string 文字
}
public Color ItemColor { get; set; }
public string Message { get; set; }
}
/// <summary>
/// ListBox繪畫底圖的事件功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SearchListBoxResult_DrawItem(object sender, DrawItemEventArgs e)
{
ListBox Temp = new ListBox();
for (int i = tabPage3.Controls.Count - 1; i >= 0; i--)
{
if (this.tabPage3.Controls[i].Name == "SearchListBoxResult_ListBox")
Temp = (ListBox)this.tabPage3.Controls[i];
}
MyListBoxItem item = Temp.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem
if (item != null)
{
e.Graphics.FillRectangle(new SolidBrush(item.ItemColor), e.Bounds);
e.Graphics.DrawString( // mDraw the appropriate text in the ListBox
item.Message, // The message linked to the item
Temp.Font, // Take the font from the listbox
new SolidBrush(Color.Black), // Set the color
0, // X pixel coordinate
e.Index * Temp.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
}
}
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言