2014-08-27 78 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)