动态创建的ListBoxItem中Label文本的修改

欢迎加入全网最大Delphi 技术交流群 682628230

在Delphi FMX中,当尝试通过代码动态查找并修改嵌套在多个布局(Layouts)中的Label控件文本时遇到问题。该问题涉及到从ListBoxItem开始,经过三层结构(ListBoxItem -> Layout -> Label),以找到特定的Label并更改其文本。

原代码使用了absolute关键字将不同类型控件指针强制转换为单一变量类型,导致逻辑错误和运行时异常“参数超出范围”。具体表现为,在遍历子控件时,试图访问不存在的索引。

 

避免使用absolute关键字,并且对于不同层次的控件使用独立的变量。直接进行类型检查和必要的类型转换,而不是依赖于可能导致混淆的变量重用。改进后的代码如下

var 
  e, h: Integer;
  item: TListBoxItem;
  layout: TControl;
  Lbl: TLabel;
begin
  item := ListBox1.ListItems[itemNum]; // 指定的ListBoxItem
  for h := 0 to item.ControlsCount - 1 do
  begin
    layout := item.Controls[h];
    if layout is TLayout then
    begin
      if layout.Name = 'lout3' then // 找到名为"lout3"的布局,其中包含4个Label
      begin
        for e := 0 to layout.ControlsCount - 1 do
        begin
          if layout.Controls[e] is TLabel then
          begin
            Lbl := TLabel(layout.Controls[e]);
            if Lbl.Name = 'qty1' then
            begin
              if ed_pos1.Text = '' then
                Lbl.Text := ed_pos1.TextPrompt
              else
                Lbl.Text := ed_pos1.Text;
            end;
            // 类似地处理其他Label,如qty2和qty3...
          end;
        end;
      end;
    end;
  end;
end;

此方法不仅解决了原始问题中的异常错误,还提升了代码的可读性和维护性,减少了因不当使用absolute而可能引起的其他潜在问题。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享