Visual Basic .NET - Change color of one listBox item

…衆ロ難τιáo~ 提交于 2020-01-06 15:17:10

问题


I'm making a small program in VB.NET. I have a listBox and a button. I'd like to be able to press the button and have the selected listBox item change it's foreColor to green. I've tried many ways of doing this, ranging from overriding the draw method to using a listView (listBox is much better for what I'm doing, please don't recommend that I use a listView, I've already tried it.)

At first I thought this would be simple, but it's the exact opposite and I'm very frustrated that such a simple task should be so difficult. I don't want to use any third-party controls, as I'd have to completely re-write my application.

I've tried so many different options it's not even funny. Please, can anyone offer a simpler solution?

-Q


回答1:


You need to handle DrawItem event and DrawMode=OwnerDrawFixed property.

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

    If ListBox1.SelectedIndices.Contains(e.Index) And buttonPressed Then
        e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, Brushes.Green, e.Bounds.X, e.Bounds.Y)

    Else
        e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, Brushes.Black, e.Bounds.X, e.Bounds.Y)
    End If
    If e.Index = ListBox1.Items.Count - 1 Then
        buttonPressed = False
    End If
    e.DrawFocusRectangle()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    buttonPressed = True
    ListBox1.Refresh()
End Sub


来源:https://stackoverflow.com/questions/5240612/visual-basic-net-change-color-of-one-listbox-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!