2014-08-27 69 views
0

我可以使用DrawItem事件为列表框项目设置forecolor。但是,例如,如果我的列表包含单个红色的颜色项目,则一旦我添加了下一个具有所需绿色的颜色,我就无法保留第一个带有红色的项目。假设我可以设置颜色,但我需要先获取项目颜色。如何获得列表框项目的forecolor?谢谢。VB .Net更改列表框中某些项目的forecolor

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

     e.DrawBackground() 

     If e.Index = listBoxSize Then 
      e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, Brushes.Green, e.Bounds.X, e.Bounds.Y) 
     Else 
      Using br = New SolidBrush(e.ForeColor) 
       e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, br, e.Bounds.X, e.Bounds.Y) 
      End Using 
     End If 
     e.DrawFocusRectangle() 

    End Sub 
+0

你想完成什么?交替的颜色? – Grim 2014-08-27 12:06:30

+1

我想,您将需要一个列表或数组来跟踪每个项目的颜色。例如,除非LB本身的默认值为Red,否则Red没有任何内容。 – Plutonix 2014-08-27 12:08:05

回答

1

您可以使用Dictionary(TKey, TValue)类来存储颜色所列项目

Dim colors As New Dictionary(Of Integer, Color) 

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

    e.DrawBackground() 
    Dim clr As Color = e.ForeColor 
    If e.Index = listBoxSize Then 
     clr = Colors.Green 

    Using br = New SolidBrush(clr) 
      e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, br, e.Bounds.X, e.Bounds.Y) 
    End Using 
    colors.Add(e.Index, clr) 

    e.DrawFocusRectangle() 
End Sub 

现在你可以retrive通过列表指数的颜色。

Dim clr Color = colors(listBox1.SelectedIndex)