学习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(); }
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
从这个例子,我们发现在C#下面重画控件,比在vc++6.0中定义自绘方便多了
【编辑推荐】