淺析VB.NET實(shí)現(xiàn)下拉列表的折行顯示
VB.NET有很多值得學(xué)習(xí)的地方,這里我們主要介紹VB.NET實(shí)現(xiàn)下拉列表,包括介紹控件進(jìn)行改進(jìn)等方面。
.NET是Microsoft公司提供解決未來(lái)計(jì)算需要的工具。在.NET Framework中提供了許多控件,可以解決編程中用戶(hù)界面的設(shè)計(jì)和實(shí)現(xiàn),但在實(shí)際應(yīng)用中可能需要對(duì)系統(tǒng)提供的控件進(jìn)行改進(jìn),如下拉列表不能折行顯示。本文將介紹用VB.NET實(shí)現(xiàn)下拉列表折行顯示。
設(shè)計(jì)能自動(dòng)折行的下拉列表
VB.NET實(shí)現(xiàn)下拉列表,在ComboBox控件中每項(xiàng)占用一行,如果有選擇項(xiàng)的內(nèi)容長(zhǎng)度超過(guò)下拉列表的寬度,則超過(guò)部分不顯示,這樣就可能造成用戶(hù)所見(jiàn)的內(nèi)容不完全而無(wú)法選擇的情況。我們對(duì)該控件進(jìn)行改進(jìn),當(dāng)一行顯示不完全某項(xiàng)時(shí)進(jìn)行折行顯示,為了防止用戶(hù)將折行的項(xiàng)誤認(rèn)為是兩個(gè)選擇項(xiàng),我們將不同的選項(xiàng)用相互間隔的顏色區(qū)分。類(lèi)代碼如下:
- Public Class myComboBox
- Inherits System.Windows.Forms.ComboBox
- #Region " Windows 窗體設(shè)計(jì)器生成的代碼 "
- …
- #End Region
- '下面代碼用不同的顏色顯示選項(xiàng)
- Private Sub myComboBox_DrawItem(ByVal sender As Object,
ByVal e As _ System.Windows.Forms.DrawItemEventArgs) Handles MyBase.DrawItem- If e.Index < 0 Then Exit Sub
- Dim txtColor As SolidBrush
- Dim bgColor As SolidBrush
- Dim txtfnt As Font
- txtColor = New SolidBrush(Color.Black)
- If e.Index / 2 = CInt(e.Index / 2) Then
- bgColor = New SolidBrush(Color.White)
- Else
- bgColor = New SolidBrush(Color.LightYellow)
- End If
- If e.State And DrawItemState.Selected Then
- txtColor = New SolidBrush(Color.Blue)
- End If
- e.Graphics.FillRectangle(bgColor, e.Bounds)
- e.Graphics.DrawRectangle(Pens.Black, e.Bounds)
- Dim r As New RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)
- e.Graphics.DrawString(Items(e.Index).ToString, Me.Font, txtColor, r)
- End Sub
- '下面代碼計(jì)算每行選項(xiàng)需要的尺寸
- Private Sub myComboBox_MeasureItem(ByVal sender As Object,
ByVal e As _ System.Windows.Forms.MeasureItemEventArgs) Handles MyBase.MeasureItem- Dim lsize As SizeF
- lsize = e.Graphics.MeasureString(Items(e.Index).ToString, Me.Font, New SizeF(Me.Width, 200))
- e.ItemHeight = lsize.Height
- e.ItemWidth = lsize.Width
- End Sub
- End Class
以上介紹VB.NET實(shí)現(xiàn)下拉列表折行顯示。
【編輯推薦】