Question

I have added a TImage to the style of TListBoxItem.

If I add to a TListBox, it works. If I add to a TComboBox, it doesn't works. I can't even change the height if the item in a TComboBox.

Here my sample code:

procedure TMainForm.FormCreate(Sender: TObject);
const
  BitmapFile : String = 'F:\testimage.png';
var
  ItemText : TText;
  ItemImage   : TImage;
  ListBoxItem : TListBoxItem;
  button : TButton;
begin

  ListBoxItem := TListBoxItem.Create(nil);
  ListBoxItem.Parent := CBoxHeadMenuLanguage;

  ListBoxItem.StyleLookup := 'ListBoxItemIconStyle';
  ListBoxItem.Height := 50; //just for test

  ItemText := ListBoxItem.FindStyleResource('text') as TText;
  if Assigned(ItemText) then ItemText.Text := 'Hello World!';

  ItemImage := ListBoxItem.FindStyleResource('image') as TImage;
  if Assigned(ItemImage) then If FileExists(BitmapFile) Then ItemImage.Bitmap.LoadFromFile(BitmapFile);
end;
Was it helpful?

Solution

You really shouldn't be doing styling stuff in FormCreate since styles are applied on an as-needed basis and can be removed and reapplied at any time.

Instead you'll need to use either OnApplyStyleLookup event or the ApplyStyle method. I recommend subclassing TListBox and using the latter and add a property to store the bitmap.

An outline class declaration would be:

type TBitmapLBItem = class(TListBoxItem)
  private
    FBitmap: TBitmap;
  protected
    procedure ApplyStyle;override;
  public
    property Bitmap: TBitmap read FBitmap write SetBitmap;
  end;

Use FindStyleResource etc both in ApplyStyle and SetBitmap (or create a shared method to do it).

And in FormCreate create items of your new class and set the Bitmap properties as appropriate.

As for the height problem, try setting the ItemHeight property of the combo box. If you want a variety of heights within the list you're probably out of luck.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top