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