分析进步
1,可以看出 AddHandler list.DrawItem,sun****** 这里是转换过来的,其实这里是一个事件过程
2,可以优化到第二个版本,代码易读性更强比较容易看。
最开始的版本
Public Shared Sub Bind(ByVal list As Windows.Forms.ComboBox, ByVal itemHeight As Integer)
list.DropDownStyle = ComboBoxStyle.DropDownList
list.ItemHeight = itemHeight
list.DrawMode = DrawMode.OwnerDrawFixed
AddHandler list.DrawItem, Sub(sender As Object, e As DrawItemEventArgs)
If e.Index < 0 Then
Return
End If
e.DrawBackground()
e.DrawFocusRectangle()
e.Graphics.DrawString(list.Items(e.Index).ToString(), e.Font, New SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 3)
End Sub
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Bind(ComboBox1, 20)
End Sub
End Class
优化后的版本
''' <summary>
'''1,窗体加载的时候绑定ChangeComBoxHeight
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
ChangeComBoxHeight(ComboBox1, 20)
End Sub
''' <summary>
''' 2,修改COMBOX的属性
''' </summary>
''' <param name="csComboBox"></param>
''' <param name="itemHeight"></param>
Private Sub ChangeComBoxHeight(ByVal csComboBox As Windows.Forms.ComboBox, ByVal itemHeight As Integer)
'设置DropDownStyle属性
csComboBox.DropDownStyle = ComboBoxStyle.DropDownList
'设置高度
csComboBox.ItemHeight = itemHeight
'设置DrawMode
csComboBox.DrawMode = DrawMode.OwnerDrawFixed
AddHandler csComboBox.DrawItem, AddressOf ComboBox_DrawItemold
End Sub
''' <summary>
''' 执行DrawItemold事件
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub ComboBox_DrawItemold(sender As Object, e As DrawItemEventArgs)
If e.Index < 0 Then
Return
End If
e.DrawBackground()
e.DrawFocusRectangle()
e.Graphics.DrawString(sender.Items(e.Index).ToString(), e.Font, New SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 3)
End Sub