【问题标题】:Display list of colors and their names in a combobox在组合框中显示颜色列表及其名称
【发布时间】:2020-05-26 15:44:23
【问题描述】:

我正在尝试在组合框中显示颜色列表。框中的每一项都包含一种颜色的名称,后缀为一个矩形,该矩形填充了相应的颜色,如项目here 所示。

该项目是用 C# 编写的。我不懂 c#,所以我将代码转换为 vb .net,如下所示。

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    Dim ColorList As ArrayList = New ArrayList()
    Dim colorType As Type = GetType(System.Drawing.Color)
    Dim propInfoList As PropertyInfo() = colorType.GetProperties(BindingFlags.[Static] Or BindingFlags.DeclaredOnly Or BindingFlags.[Public])

    For Each c As PropertyInfo In propInfoList
        ComboBox1.Items.Add(c.Name)
    Next
End Sub

Private Sub Combobox1_DrawItem(ByVal sender As Object, ByVal e As DrawItemEventArgs) Handles ComboBox1.DrawItem
    Dim g As Graphics = e.Graphics
    Dim rect As Rectangle = e.Bounds

    If e.Index >= 0 Then
        Dim n As String = (CType(sender, ComboBox)).Items(e.Index).ToString()
        Dim f As Font = New Font("Arial", 9, FontStyle.Regular)
        Dim c As Color = Color.FromName(n)
        Dim b As Brush = New SolidBrush(c)
        g.DrawString(n, f, Brushes.Black, rect.X, rect.Top)
        g.FillRectangle(Brushes.Blue, rect.X + 110, rect.Y + 5, rect.Width - 10, rect.Height - 10)
    End If
End Sub

当我执行上述代码时,组合框Combobox1 仅显示带有颜色名称的项目。我上面链接的项目中没有显示彩色矩形。
是什么导致矩形不显示?
我尝试将Combobox1DrawMode 设置为所有可用的DrawModes。没有任何效果。

注意,我使用Telerik's code converter 将 c# 代码转换为 vb .net 代码。

【问题讨论】:

  • 您是否按照那篇文章的背景部分中的说明进行操作? IE。将 DrawMode 设置为 DrawModeFixed?
  • @Steve 在将绘制模式设置为 OwnerDrawFixed 后它正在工作。谢谢。
  • @Steve 但是当组合框的 DropDownStyle 设置为“简单”时,矩形再次消失
  • 请不要在新代码中使用 ArrayList。见docs.microsoft.com/en-us/dotnet/api/…
  • @Mary 不,我没有使用 ArrayList。我已经从我的代码中删除了按钮单击事件。无论如何感谢您的建议。这很有帮助。

标签: vb.net graphics combobox rectangles drawrectangle


【解决方案1】:
Dim N As String = (CType(sender, ComboBox)).Items(e.Index).ToString()
Dim F As Font = New Font("Arial", 10, FontStyle.Regular)
Dim B As Brush = New SolidBrush(e.ForeColor)
Dim C As Color = Color.FromName(N)
Dim P As Brush = New SolidBrush(C)
Dim L As Pen = New Pen(e.ForeColor)
Dim R1 As Rectangle = New Rectangle(e.Bounds.Left + 2, e.Bounds.Top + 2, 50, e.Bounds.Height - 4)
Dim R2 As Rectangle = New Rectangle(e.Bounds.Left + 3, e.Bounds.Top + 3, 48, e.Bounds.Height - 6)
Dim R3 As Rectangle = New Rectangle(e.Bounds.Left + 2, e.Bounds.Top + 2, 50, e.Bounds.Height - 4)
Dim R4 As Rectangle = New Rectangle(e.Bounds.Left + 2, e.Bounds.Top + 2, 50, e.Bounds.Height - 4)
e.Graphics.DrawRectangle(L, R1)
e.Graphics.FillRectangle(P, R2)
e.Graphics.DrawString(N, F, B, e.Bounds.Left + 65, e.Bounds.Top + 2)

e.DrawFocusRectangle()

【讨论】:

  • 虽然此代码可能会解决问题,但 including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
猜你喜欢
  • 2012-09-05
  • 2016-07-15
  • 1970-01-01
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-06
相关资源
最近更新 更多