有顏色的世界:C# listbox的item顏色改變方法
大家都喜歡多彩的世界,筆者也想運(yùn)用鍵盤來敲出一個(gè)多彩的畫面,下面給大家介紹一種C# listbox的item顏色改變的方法。
(1)C# listbox實(shí)現(xiàn)變色之前,需要先設(shè)置屬性:
該事件由所有者描述的ListBox使用。僅當(dāng)DrawMode屬性設(shè)置為DrawMode.OwnerDrawFixed或DrawMode.OwnerDrawVariable時(shí),才引發(fā)該事件??梢允褂迷撌录韴?zhí)行在ListBox中繪制項(xiàng)所需的任務(wù)。
如果具有大小可變的項(xiàng)(當(dāng)DrawMode屬性設(shè)置為DrawMode.OwnerDrawVariable時(shí)),在繪制項(xiàng)前,引發(fā)MeasureItem事件??梢詾镸easureItem事件創(chuàng)建事件處理程序,以在DrawItem事件的事件處理程序中指定要繪制的項(xiàng)的大小。有關(guān)處理事件的更多信息,請(qǐng)參見使用事件。
(2)重寫C# listbox的drawitem事件
- privatevoidlistBox1_DrawItem(objectsender,System.Windows.Forms.DrawItemEventArgse){//SettheDrawModepropertytodrawfixedsizeditems.
- listBox1.DrawMode=DrawMode.OwnerDrawFixed;
- //DrawthebackgroundoftheListBoxcontrolforeachitem.
- e.DrawBackground();//Definethedefaultcolorofthebrushasblack.
- BrushmyBrush=Brushes.Black;
- //Determinethecolorofthebrushtodraweachitembasedontheindexoftheitemtodraw.
- switch(e.Index){case0:myBrush=Brushes.Red;break;
- case1:myBrush=Brushes.Orange;break;
- case2:myBrush=Brushes.Purple;break;}
- //DrawthecurrentitemtextbasedonthecurrentFontandthecustombrushsettings.
- e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),e.Font,myBrush,
- e.Bounds,StringFormat.GenericDefault);
- //IftheListBoxhasfocus,drawafocusrectanglearoundtheselecteditem.
- e.DrawFocusRectangle();}
(3)從C# listbox的item顏色改變的例子中,我們發(fā)現(xiàn)在c#下面重畫控件,比在vc++6.0中定義自繪方便多了。
【編輯推薦】