下面是继承的 ComboBox 的代码。问题是 ComboBox 被PopulateComboBox()
多次填充 ( )。
编辑:我接受了Amit Mittal的建议(在下面找到他的答案)并实施了ISupportInitialize
. 现在PopulateComboBox()
只在运行时调用,就像它应该的那样。
通过这种实现,项目应该在运行时填充,并在退出时销毁。但是,设计器本身在运行时创建这些值时存储这些值,而不是在运行时销毁。
是否有一个优雅的解决方案来实现此代码?
Public Class ComboBoxExColors
Inherits ComboBox
Implements ISupportInitialize
Public Sub New()
MyBase.New()
Me.Size = New Size(146, 23)
Me.DropDownStyle = ComboBoxStyle.DropDownList
Me.MaxDropDownItems = 16
End Sub
Public Sub BeginInit() Implements System.ComponentModel.ISupportInitialize.BeginInit
' Do nothing?
End Sub
Public Sub EndInit() Implements System.ComponentModel.ISupportInitialize.EndInit
Me.DrawMode = DrawMode.OwnerDrawVariable ' fixed or variable?
Me.PopulateComboBox()
End Sub
Public Sub PopulateComboBox()
'Me.Items.Clear() ' rather than forcing items to be cleared, is there a more elegant solution to the implementation of this code, rather than forcing an item clear that shouldn't exist to begin with?
Me.Items.Add("Default")
Me.Items.Add("Custom")
Dim KnownColors() As String = System.Enum.GetNames(GetType(System.Drawing.KnownColor)) ' get all colors
For Each c As String In KnownColors ' add non system colors
If Not Color.FromName(c).IsSystemColor Then
Me.Items.Add(c)
End If
Next c
End Sub
Protected Overrides Sub OnDrawItem(ByVal e As DrawItemEventArgs)
' this draws each item onto the control
If e.Index > -1 Then
Dim item As String = Me.Items(e.Index).ToString
e.DrawBackground()
e.Graphics.DrawString(item, e.Font, SystemBrushes.WindowText, e.Bounds.X, e.Bounds.Y)
e.DrawFocusRectangle()
End If
End Sub
End Class