我看到这篇文章正在寻找解决这个问题的方法,但找不到正是我需要的解决方案。我进行了一些试验,并提出了适用于 Visual Basic .NET 的解决方案,该解决方案融合了本文中 Adam 的代码和其他 here 的代码。
我将展示两种不同的方法,并简要讨论优点和缺点:
- 挂钩 DrawItem 事件;
- 创建自定义控件。
=============================方法1 ================= ===============
此方法只是简单地挂钩 ComboBox 的 DrawItem 事件,因此不需要自定义控件。
第 1 步
像往常一样添加您的 ComboBox。在其属性中,将 DrawMode 更改为 OwnerDrawFixed。如果你忘记了这一点,下一部分将无济于事。当然,也可以将您的 DropDownStyle 更改为 DropDownList。
第 2 步
添加自定义处理程序:
Private Sub ComboBox1_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ComboBox1.DrawItem
Dim cmb = CType(sender, ComboBox)
If cmb Is Nothing Then Return
Dim index As Integer = If(e.Index >= 0, e.Index, -1)
Dim brush As Brush = If(((e.State And DrawItemState.Selected) > 0), SystemBrushes.HighlightText, New SolidBrush(cmb.ForeColor))
e.DrawBackground()
If index <> -1 Then
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit
e.Graphics.DrawString(cmb.Items(index).ToString(), e.Font, brush, e.Bounds, StringFormat.GenericDefault)
End If
e.DrawFocusRectangle()
End Sub
注意
您可以使用单个 sub 来处理多个 ComboBox,但您必须记住手动将它们添加到 Handles。
=============================方法2 ================= ===============
此方法依赖于从 ComboBox 继承的自定义控件。通过将这个自定义控件添加到我们的表单中,而不是普通的 ComboBox,它就可以工作了——我们不必担心Handles 语句。如果您打算拥有多个 ComboBox,这可能是可行的方法。
第 1 步
通过右键单击您的项目添加自定义控件,添加,新建项目,然后选择自定义控件(Windows 窗体)。我将我的命名为 ComboBoxClean。
第 2 步
在文件 ComboBoxClean.vb 中,将自动生成的代码替换为:
Public Class ComboBoxClean
Inherits ComboBox
Public Sub New()
DropDownStyle = ComboBoxStyle.DropDownList
DrawMode = DrawMode.OwnerDrawFixed
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
MyBase.OnPaint(e)
End Sub
Protected Overrides Sub OnDrawItem(ByVal e As DrawItemEventArgs)
Dim index As Integer = If(e.Index >= 0, e.Index, -1)
Dim brush As Brush = If(((e.State And DrawItemState.Selected) > 0), SystemBrushes.HighlightText, New SolidBrush(ForeColor))
e.DrawBackground()
If index <> -1 Then
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit
e.Graphics.DrawString(Items(index).ToString(), e.Font, brush, e.Bounds, StringFormat.GenericDefault)
End If
e.DrawFocusRectangle()
End Sub
End Class
第 3 步
在解决方案资源管理器中,单击显示所有文件。打开 ComboBoxClean.Designer.vb。
用这个替换现有的 Inherits 语句:
Inherits ComboBox
注意事项
- 您应该在尝试使用它之前继续构建,以确保一切正常。
- 在工具箱中,您的自定义控件将不在普通控件列表中。您当前的解决方案应该在那里有自己的组件部分,您应该在其中找到新控件。只需将其拖到表单上,然后像使用普通组合框一样使用它。
- 子
New 会自动为我们进行重要的属性更改,否则我们每次添加新的 ComboBox 时都必须手动进行。