本文簡述了Delphi實作Listbox中的item根據內容顯示不同顏色的方法,實作步驟如下:
ListBox1 的Style 屬性改為lbOwnerDrawVariable
在ListBox的OnDrawItem事件,根據item的值,改變Canvas屬性
範例程式碼如下:
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);begin //字體用原來預設的顏色if Odd(index) then //當items的index為奇數時的顏色begin listbox1 .Canvas.Brush.Color:=clwindow; ListBox1.Canvas.TextRect(Rect,rect.Left,Rect.Top,ListBox1.Items[index]); end else //當items的index為偶數時的顏色begin listbox1.Canvas.Brush.Color:=clinactivecaptiontext; ListBox1 .Canvas.TextRect(Rect,rect.Left,Rect.Top,ListBox1.Items[index]); end; if odSelected in state then //當選取時的顏色begin listbox1.Canvas.Brush.Color:=clhighlight; ListBox1.Canvas.TextRect(Rect,rect.Left,Rect.Top,ListBox1.Items[index]); end ;end;