delphi firemonkey使用 TListbox 自定义列表数据(二StyleBook方式实现)

上一篇用设计好界面后用代码添加稍微有些麻烦,所以改为用StyleBook设计好后添加Item

界面上添加ListBox后改Item高度为100

右键添加一条空白记录,观察高度,并且方便自定义编辑style样式

默认添加一条ListBoxItem1Style1的样式,添加Layout布局到这个样式下,并且添加需要的控件进去

layout布局改为如下显示,演示用的文本及图形显示,也可以添加任何控件进去,作为演示用添加的多了就稍显复杂

关闭设计界面时会提示是否应用

窗口上的按钮事件手动添加一条记录,TText提示找不到需要uses FMX.Objects

procedure TForm1.Button1Click(Sender: TObject);
const
BitmapFile: string = 'D:\People\1.png';  // 图片文件路径

var
ListBoxItem: TListBoxItem;
ItemText: TText;
ItemImage: TImage;

begin
ListBoxItem := TListBoxItem.Create(nil);
ListBoxItem.Parent := ListBox1;
ListBoxItem.StyleLookup := 'ListBoxItem1Style1';  // 设置列表项的样式

ItemText := ListBoxItem.FindStyleResource('text1') as TText;  // 获取列表项中的文本控件
if Assigned(ItemText) then
ItemText.Text := '张三';  // 设置文本控件的文本内容为'张三'

ItemText := ListBoxItem.FindStyleResource('text2') as TText;  // 获取列表项中的文本控件
if Assigned(ItemText) then
ItemText.Text := '48';  // 设置文本控件的文本内容为'48'

ItemImage := ListBoxItem.FindStyleResource('Image1Style') as TImage;  // 获取列表项中的图片控件
if Assigned(ItemImage) then
if FileExists(BitmapFile) then
ItemImage.Bitmap.LoadFromFile(BitmapFile);  // 加载指定路径的图片文件到图片控件中
end;

执行后效果如下

 点击后取值,仅做示例

procedure TForm1.ListBox1ItemClick(const Sender: TCustomListBox; const Item: TListBoxItem);
var
  ItemText1: TText;
  ItemText2: TText;
  ItemImage: TImage;
begin
// 从被点击的列表框项中获取值
  ItemText1 := Item.FindStyleResource('text1') as TText;
  ItemText2 := Item.FindStyleResource('text2') as TText;
  ItemImage := Item.FindStyleResource('Image1Style') as TImage;

  if Assigned(ItemText1) then
    ShowMessage('文本1: ' + ItemText1.Text);

  if Assigned(ItemText2) then
    ShowMessage('文本2: ' + ItemText2.Text);

  if Assigned(ItemImage) and Assigned(ItemImage.Bitmap) then
    ShowMessage('图像: 已加载')
  else
    ShowMessage('图像: 未加载');
end;

 可以放任何自己需要的控件上去,如图

 演示代码

procedure TForm1.Button2Click(Sender: TObject);
var
  ListBoxItem: TListBoxItem;
  ItemText: TText;
  ItemProgress: TProgressBar;
  i: Integer;
begin
  if ListBox1.Items.Count > 0 then
  begin
    for i := 0 to Pred(ListBox1.Items.Count) do
    begin
      ListBoxItem := ListBox1.ItemByIndex(i);
      ItemText := ListBoxItem.FindStyleResource('Caption') as TText;
      if Assigned(ItemText) then
        ItemText.Text := 'Hello World! ' + IntToStr(i);

      ItemText := ListBoxItem.FindStyleResource('SubItem1') as TText;
      if Assigned(ItemText) then
        ItemText.Text := 'SubItem1 ' + IntToStr(i);
      ItemText := ListBoxItem.FindStyleResource('SubItem2') as TText;
      if Assigned(ItemText) then
        ItemText.Text := 'SubItem2 ' + IntToStr(i);

      ItemProgress := ListBoxItem.FindStyleResource('Progress') as TProgressBar;
      if Assigned(ItemProgress) then
        ItemProgress.Value := Random(100);
    end;
  end;
end;

 

posted @ 2024-01-14 23:22  liessay  阅读(89)  评论(0编辑  收藏  举报