【发布时间】:2012-06-27 22:59:54
【问题描述】:
以下是继承的 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
【问题讨论】:
-
我已尝试按原样使用您修改后的 ComboBoxExColors 类,但看不到任何重复项。可能是 Designer.vb 的旧代码(其中明确添加了项目)仍然存在。我认为重复项目除此之外没有其他原因。要删除旧代码,请从设计器表面删除控件,重新构建解决方案,然后再次将 ComboBoxExColors 控件放在表面上。要进行测试,您还可以添加一个新的虚拟测试表单并在其上放置 ComboBoxExColors。
-
每次对代码进行调整时,我都会从设计器中移除控件。我运行了一次应用程序,它很好,我查看了设计器集合并且项目在那里。一旦我再次运行该应用程序,这些项目就会列出两次。我不明白为什么设计器要存储在运行时添加的值。如果我在添加之前将其设置为清除项目,则它可以工作。但是对于我没有正确实现的代码,或者它可能是一个错误,这不是一个优雅的解决方案。
-
您是否尝试过使用空白的虚拟测试表?这个问题是否也会重复?在我的最后,你的新代码不会发生这种情况,而当你使用构造函数时我可以重现它。
标签: .net vb.net winforms combobox visual-studio-2008-sp1