本文介绍了Visual Basic .NET - 更改一个列表框项的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 VB.NET 编写一个小程序.我有一个列表框和一个按钮.我希望能够按下按钮并让选定的列表框项目将其前景色更改为绿色.我已经尝试了很多方法,从覆盖draw方法到使用listView(listBox对于我正在做的事情要好得多,请不要推荐我使用listView,我已经尝试过了.)

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

推荐答案

您需要处理 DrawItem 事件和 DrawMode=OwnerDrawFixed 属性.

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

这篇关于Visual Basic .NET - 更改一个列表框项的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 20:03
查看更多