【问题标题】:Combobox Backcolor with Dropdownlist is possible?可以使用带有下拉列表的组合框背景颜色吗?
【发布时间】:2016-12-31 18:12:38
【问题描述】:
组合框中的项目不出现。这是我的代码:
ComboBox1.BackColor = Color.White
ComboBox1.ForeColor = Color.Black
ComboBox1.DrawMode = DrawMode.OwnerDrawFixed
ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
ComboBox1.FlatStyle = FlatStyle.Standard
ComboBox1.Items.Add("LIne 1")
ComboBox1.Items.Add("LIne 2")
ComboBox1.Items.Add("LIne 3")
ComboBox1.Items.Add("LIne 4")
ComboBox1.Items.Add("LIne 5")
ComboBox1.Items.Add("LIne 6")
ComboBox1.Text = ComboBox1.Items(0)
这是我执行时看到的:
我的代码做错了什么?
【问题讨论】:
标签:
vb.net
winforms
drop-down-menu
combobox
backcolor
【解决方案1】:
这是导致您看不到任何项目的线:
ComboBox1.DrawMode = DrawMode.OwnerDrawFixed
那是因为你用那条线告诉组合框:嘿,我正在自己画图。从那一刻起,当 Combobox 想要绘制某些东西时,它会引发事件 DrawItem,您可以订阅它并处理它。在这种情况下的处理意味着:在事件中给定的 Graphics 对象上绘制一些东西。
这是一个简单的实现:
Private Sub ComboBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ComboBox1.DrawItem
Dim Brush = Brushes.Black
If (e.State And DrawItemState.ComboBoxEdit) = DrawItemState.ComboBoxEdit Then
Brush = Brushes.Yellow
End If
If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
Brush = Brushes.SteelBlue
End If
Dim Point = New Point(2, e.Index * e.Bounds.Height + 1)
' reset
e.Graphics.FillRectangle(New SolidBrush(ComboBox1.BackColor),
New Rectangle(
Point,
e.Bounds.Size))
' draw content
e.Graphics.DrawString(
ComboBox1.Items(e.Index).ToString(),
ComboBox1.Font,
Brush,
Point)
End Sub
如果您不打算绘制自己的项目,您当然可以删除 DrawMode 线...
这是我的代码的结果: