Der Effekt, sich abwechselnder Zeilenfarben[meta]Zeile, Farbe[/meta], ist dann sinnvoll, wenn die die Zeilen besonders lang sind. Dann ist es leichter dem Text zu folgen. Hier ein Tipp wie man diesen Effekt bei einer ListBox nutzt. Dazu nutzt man das Ereignis OnDrawItem der ListBox. Diese bietet ein Canvas zum Zeichnen und ein Rect-Bereich in den gezeichnet werden darf.
Zuerst muß allerdings die
TListBox.Style Eigenschaft auf
lbOwnerDrawFixed (oder lbOwnerDrawVariable bei variablen Höhen) gestellt werden. Wenn man das nicht macht, dann wird nicht gezeichnet.
Wichtig!
Delphi-Quelltext
1: 2: 3:
| ... ListBox1.Style := lbOwnerDrawFixed; ... |
Entweder im Code einstellen oder bereits in Objektinspektor.
Die Prozedur ist allgemein aufgebaut und kann aus jeder OnDrawItem Prozedur aufgerufen werden. Die Parameter der Prozedur sind die gleichen wie bei der OnDrawItem Prozedur. Man muß die Variablenbezeichnungen einfach nur übertragen:
Delphi-Quelltext
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21:
| procedure DrawListBoxZC(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); const Col1: array [Boolean] of TColor = ($00F8F8F8, clWindow); Col2: array [Boolean] of TColor = (clInactiveCaptionText, clWindowText); var TopDif: Integer; begin with (Control as TListbox) do begin if odSelected in State then Canvas.Font.Color := clCaptionText else begin Canvas.Brush.Color := Col1[Odd(Index)]; Canvas.Font.Color := Col2[(Control as TListbox).Enabled]; end; TopDif := (ItemHeight div 2) - (Canvas.TextHeight(#32) div 2); Canvas.TextRect(Rect, Rect.Left, Rect.Top + TopDif, Items[Index]); end; end; |
Beispiel:
Die DrawListBox Prozedur (oben) ist universal einsetzbar und kann aus verschieden Prozeduren gleichzeitig aufgerufen werden. Hier aus der OnDrawItem Ereignisprozedur der ListBox1:
Delphi-Quelltext
1: 2: 3: 4: 5:
| procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin DrawListBoxZC(Control, Index, Rect, State); end; |
Moderiert von jasocul: Anpassungen an den Style-Guide
Moderiert von jasocul: Beitrag geprüft am 13.05.2006