【问题标题】:Why are my TListBox items not changing their color?为什么我的 TListBox 项目没有改变颜色?
【发布时间】:2015-10-26 11:19:15
【问题描述】:

这就是我从位于本地服务器上的列表中获取一些项目的方式。

我认为它仍然需要一些重构(很抱歉在Delphi 是这样的初学者),但是我想更好地理解为什么ListItem 颜色 没有被改变。 p>

我做了一些调试,发现if 条件对每种颜色都工作正常,ListItem 正在接收它,但我可能得到了错误的参考或使用了错误的参考属性来改变颜色。

这是完整的代码:

procedure TFormLogin.TimerGetListTimer(Sender: TObject);
var
  genset_response: String;
  genset_amount: Integer;

  i: Integer;
  str_array: TStringDynArray;
  lb_item: TListBoxItem;

begin

  // Run this timer only 1 time for now
  TimerGetList.Enabled := false;

  // Clear all List items
  lb_gensets.Clear;

  // GET_LIST command to server
  IdTCPClient1.IOHandler.WriteLn('GET_LIST');
  // Server returns the List in a String
  genset_response := IdTCPClient1.IOHandler.ReadLn();

  // Remove all " from the String
  genset_response := StringReplace(genset_response, '"', '',
    [rfReplaceAll, rfIgnoreCase]);

  // Separate data by divider
  str_array := SplitString(genset_response, '|');

  // Get how many items
  genset_amount := StrToInt(str_array[1]);

  // Populate the List
  for i := 0 to (genset_amount - 1) do
  begin

    if (i = 0) then
    begin
      lb_gensets.Items.Add(str_array[2]);
    end
    else
    begin
      // Add items
      lb_gensets.Items.Add(str_array[i + 2]);

    end;

    // Get current ListItem
    lb_item := lb_gensets.ListItems[i];

    if (lb_item.Text.Contains('Online')) then
    begin
      // Set online items to Green color
      lb_item.TextSettings.FontColor := TAlphaColors.Mediumseagreen;
    end;

    if (lb_item.Text.Contains('OFF LINE')) then
    begin
      // Set Off Line items to Red color
      lb_item.TextSettings.FontColor := TAlphaColors.Red;
    end;

    // End of FOR
  end;

end;

【问题讨论】:

  • 也许您的列表已排序,因此i 变量不再与列表的索引匹配。 lb_gensets.ListItems[i]lb_gensets.ItemByIndex(i) 的作用相同。这种情况下申请this solution比较安全

标签: delphi firemonkey listboxitem


【解决方案1】:

默认情况下,控件使用当前样式项的值(请参阅StyleLookup 属性)。

要使用自定义字体颜色,您必须从 ListItem 中排除 TStyledSetting.FontColor

lb_item.StyledSettings:=lb_item.StyledSettings - [TStyledSetting.FontColor];
lb_item.TextSettings.FontColor := TAlphaColors.Red;

【讨论】:

  • 获取项目参考的正确方法是:lb_item := lb_gensets.ItemByIndex(i);
猜你喜欢
  • 1970-01-01
  • 2011-11-21
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
相关资源
最近更新 更多