vb.net 更改包含 drawitem 上特定字符串的列表框上特定项目的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15936006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:48:54  来源:igfitidea点击:

Change color of specific item on listbox that contains a specific string on drawitem

vb.netlistbox

提问by WozzeC

i want to change the color of item that contains a specific string

我想更改包含特定字符串的项目的颜色

Private Sub ListBox2_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox2.DrawItem
    e.DrawBackground()
    If DrawItemState.Selected.ToString.Contains("specific string") Then
        e.Graphics.FillRectangle(Brushes.LightGreen, e.Bounds)
    End If

    e.DrawFocusRectangle()

that is my code but not working

这是我的代码但不起作用

回答by WozzeC

Alright, first you need to set the property DrawMode of the list box to "OwnerDrawFixed" instead of Normal. Otherwise you will never get the DrawItem event to fire. When that is done it is all pretty straight forward.

好的,首先您需要将列表框的属性DrawMode 设置为“OwnerDrawFixed”而不是Normal。否则,您将永远不会触发 DrawItem 事件。完成后,一切都非常简单。

Private Sub ListBox1_DrawItem(sender As System.Object, e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
    e.DrawBackground()

    If ListBox1.Items(e.Index).ToString() = "herp" Then

        e.Graphics.FillRectangle(Brushes.LightGreen, e.Bounds)
    End If
    e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), e.Font, Brushes.Black, New System.Drawing.PointF(e.Bounds.X, e.Bounds.Y))
    e.DrawFocusRectangle()
End Sub

You will have to touch this up with different colors if selected. But this should be enough for you to continue to work on. You were close, keep that in mind. :)

如果选择,您将不得不用不同的颜色来修饰它。但这应该足以让您继续工作。你很接近,记住这一点。:)