文/马金虎
第1页:Visual Basic.NET打造个性化ListBox控件
第2页:Visual Basic.NET打造个性化ListBox控件(2)
第3页:Visual Basic.NET打造个性化ListBox控件(3)
下面就在此ListBox基础上,对其进行改造,加入个性化的东西,首先是对ListBox中的各项的字体、颜色等等进行改造。修改ListBox字体和颜色是通过DrawItem事件来实现的,使用DrawString方法把指定字体、大小、颜色在指定区域绘制文字。设定ListBox各元素的大小是通过MeasureItem事件实现的。以下是实现上述改造的具体操作步骤: 1. 设定ListBox组件的“DrawMode”属性值为“OwnerDrawVariable”。此时会发现在ListBox组件加入的“aaa”、“bbb”和“ccc”三项均不显示。这是因为当ListBox组件的“DrawMode”属性值为“OwnerDrawVariable”,绘制ListBox的工作将不在由机器自动完成,而是通过ListBox的DrawItem事件来实现。 2. 把Visual Studio .Net的当前窗口切换到Form1.vb的代码编辑窗口。 3. 在定义窗体组件的代码区中添加下列代码,下列代码是定义二个数组,此数组的成员分别是设定ListBox中各项的名称和定义各项名称的颜色。
Private sData ( ) As String = {"红色" , "蓝色" , "黄色" , "绿色" , "黄绿色" , "灰色"} '此数组是定义ListBox中各项的名称 Private sColorData ( ) As Object = {System.Drawing.Color.Red , System.Drawing.Color.Blue , System.Drawing.Color.Yellow , System.Drawing.Color.Green , System.Drawing.Color.YellowGreen , System.Drawing.Color.SlateGray} '此数组是定义各项名称对应的颜色
4. 在InitializeComponent过程中的代码后部添加下列代码,下列代码是以上面定义的sData数组来设定ListBox的各项名称:
listBox1.DataSource = sData
5. 在InitializeComponent过程之后添加下列代码,下列代码是定义ListBox的DrawItem事件,通过此事件对ListBox中各项进行重新绘制:
Private Sub listBox1_DrawItem ( ByVal sender As Object , ByVal e As System.Windows.Forms.DrawItemEventArgs ) Handles listBox1.DrawItem Dim datas As String ( ) = sData Dim rc As RectangleF = New RectangleF ( e.Bounds.X + 1 , e.Bounds.Y + 1 , e.Bounds.Width - 5 , e.Bounds.Height - 3 ) Dim rc1 As Rectangle = New Rectangle ( e.Bounds.X + 1 , e.Bounds.Y + 1 , e.Bounds.Width - 5 , e.Bounds.Height - 3 ) e.DrawBackground ( ) '在选定项目上绘制选定背景色 'e.DrawFocusRectangle ( ) Dim sf As StringFormat = New StringFormat ( ) sf.Alignment = StringAlignment.Center '设定ListBox中项目名称的在矩形区域的排列对齐方式 e.Graphics.DrawRectangle ( New Pen ( New SolidBrush ( System.Drawing.Color.Black ) , 1 ) , rc1 ) '以线条粗度为1,黑色画笔对绘制ListBox中的每一个项目的边框 e.Graphics.DrawString ( sData ( e.Index ) , New Font ( FontFamily.GenericSansSerif , 14 , FontStyle.Bold ) , New SolidBrush ( sColorData ( e.Index ) ) , rc , sf ) ' 以指定的字体大小、类型、颜色绘制ListBox项目名称 End Sub
6. 在ListBox的DrawItem事件代码之后添加下列代码,下列代码是定义ListBox的MeasureItem事件,此事件的作用是设定ListBox的各元素的大小:
Private Sub listBox1_MeasureItem ( ByVal sender As Object , ByVal e As System.Windows.Forms.MeasureItemEventArgs ) Handles listBox1.MeasureItem e.ItemHeight = 25 End Sub
至此重新绘制的ListBox第一步就完成了,保存上述的修改后,单击快捷键F5,改造后的ListBox如图02所示:
图02:【打造自己的ListBox】项目运行界面之一
[上一页]   [1]   [2]  [3]   [下一页]