淺析VB.NET實現下拉列表的折行顯示

十月 22, 2010 by
Filed under: 未分類 

VB.NET有很多值得學習的地方,這裏我們主要介紹VB.NET實現下拉列表,包括介紹控件進行改進等方面。

  .NET是Microsoft公司提供解決未來計算需要的工具。在.NET Framework中提供了許多控件,可以解決編程中用戶界面的設計和實現,但在實際應用中可能需要對系統提供的控件進行改進,如下拉列表不能折行顯示。本文將介紹用VB.NET實現下拉列表折行顯示。

  設計能自動折行的下拉列表

  VB.NET實現下拉列表,在ComboBox控件中每項占用壹行,如果有選擇項的內容長度超過下拉列表的寬度,則超過部分不顯示,這樣就可能造成用戶所見的內容不完全而無法選擇的情況。我們對該控件進行改進,當壹行顯示不完全某項時進行折行顯示,為了防止用戶將折行的項誤認為是兩個選擇項,我們將不同的選項用相互間隔的顏色區分。類代碼如下:

  Public Class myComboBox

  Inherits System.Windows.Forms.ComboBox

  #Region " Windows 窗體設計器生成的代碼 "

  …

  #End Region

  ’下面代碼用不同的顏色顯示選項

  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

  下面代碼計算每行選項需要的尺寸

  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

Comments

Tell me what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!





*