Visual Basic .NET - 更改一个listBox项目的颜色 [英] Visual Basic .NET - Change color of one listBox item

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

问题描述

我在VB.NET中创建一个小程序。我有一个listBox和一个按钮。我想能够按下按钮,并将所选的listBox项目更改为foreColor为绿色。我试过很多方法这样做,从覆盖绘制方法到使用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 - 更改一个listBox项目的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆