Skip to main content

TcxListBox.OnDrawItem Event

Enables you to paint items in a custom manner.

Declaration

property OnDrawItem: TcxListBoxDrawItemEvent read; write;

Remarks

The list box control enables you to paint items in a custom manner. For this purpose, you must set the ListStyle property to lbOwnerDrawFixed, lbOwnerDrawVariable or lbVirtualOwnerDraw. In this case, the OnDrawItem event fires for each individual item when it needs to be painted. Note that if the ListStyle property is set to one of the listed values and the OnDrawItem event is not handled, the control is painted in its usual way.

The AControl parameter specifies the list box control whose item is to be painted on the ACanvas’s surface. ACanvas provides methods to draw shapes, write text, render graphic images, etc.

The AIndex parameter identifies the processed item by its zero-based index. The bounding rectangle of the item is specified by the ARect parameter. The AState parameter provides information on whether the current item is selected, focused, etc.

Note that you can assign a custom height to each individual item. For this purpose, you need to set the ListStyle property to lbOwnerDrawVariable and handle the OnMeasureItem event. Otherwise, the height of items is specified by the ItemHeight property.

The following example shows how to implement different painting of odd and even items for a listbox control. If an item is selected (the AState parameter contains the odSelected flag), it is painted in a soft yellow color.

procedure TForm1.cxListBox1DrawItem(AControl: TcxListBox;
  ACanvas: TcxCanvas; AIndex: Integer; ARect: TRect;
  AState: TOwnerDrawState);
var
  AText: string;
  ABkGColor, ATextColor: TColor;
  ATextRect: TRect;
begin
  if odSelected in AState then
  begin
    ABkGColor := $008DEFF1;
    ATextColor := $005079BE;
  end
  else
    if Odd(AIndex) then
    begin
      ABkGColor := $00E8C5A8;
      ATextColor := clBlue;
    end
    else
      begin
        ABkGColor := $00F19F3A;
        ATextColor := clWhite;
      end;
  ACanvas.Brush.Color := ABkGColor;
  ACanvas.Font.Color := ATextColor;
  ACanvas.FillRect(ARect);
  AText := AControl.Items[AIndex];
  ATextRect := ARect;
  ATextRect.Left := ATextRect.Left + 3;
  ACanvas.DrawTexT(AText, ATextRect, 0);
end;

The result of the customization is displayed in the following image:

See Also