C# ListBox學(xué)習(xí)筆記
學(xué)習(xí)C# ListBox使用,僅當(dāng) DrawMode 屬性設(shè)置為 DrawMode.OwnerDrawFixed 或 DrawMode.OwnerDrawVariable 時,才引發(fā)該事件。可以使用該事件來執(zhí)行在C# ListBox 中繪制項所需的任務(wù)。如果具有大小可變的項(當(dāng) DrawMode 屬性設(shè)置為 DrawMode.OwnerDrawVariable 時),在繪制項前,引發(fā) MeasureItem 事件??梢詾?MeasureItem 事件創(chuàng)建事件處理程序,以在 DrawItem 事件的事件處理程序中指定要繪制的項的大小。有關(guān)處理事件的更多信息,請參見 使用事件。
重寫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();
- }
從這個例子,我們發(fā)現(xiàn)在C#下面重畫控件,比在vc++6.0中定義自繪方便多了
【編輯推薦】