按单个复选框标题读取复选框列表状态

Read check box list state by individual checkbox caption

我有几个条件可见的复选框,这意味着它们的索引不是静态的。在这种情况下,将一个动作绑定到例如CheckListBox.Checked[0] 没用,因为 0 每次都是不同的复选框。有没有办法查看标题为 foo 的复选框是否被选中?

我正在尝试这样做:

procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
begin
  if CurUninstallStep = usUninstall then
  begin
    if CheckListBox.Checked[0] then
      DelTree(ExpandConstant('{appdata}\Dagonybte\Prog1'), True, True, True)
    if CheckListBox.Checked[1] then
      DelTree(ExpandConstant('{appdata}\Dagonybte\Prog2'), True, True, True)
      { ... }
    if CheckListBox.Checked[2] then
      DelTree(ExpandConstant('{appdata}\Dagonybte\Prog3'), True, True, True)
  end
end;

通过标题查找复选框看起来是个糟糕的主意。

确实可行:

Index := CheckListBox.Items.IndexOf('Prog 1');
if (Index >= 0) and CheckListBox.Checked[Index] then
begin
  { checked }
end
  else
begin
  { does not exist or unchecked }
end;

但这不是正确的方法。

TCheckListBox is to allow generating a list of checkboxes from some data, in a loop. What is indeed the way you are using it的目的。

您尝试通过其标题查找复选框表明您想要为每个复选框编写专用代码。这违背了 TCheckListBox.

的目的

相反,在处理用户选择时,使用与生成列表时相同的方法,使用循环。

code I have shown you to generate the checkbox list 有意生成一个在 Dirs: TStringList 中具有相同索引的关联路径列表。

因此迭代该列表以及复选框以处理路径:

{ Iterate the path list }
for Index := 0 to Dirs.Count - 1 do
begin
  { Is the associated checkbox checked? }
  if CheckListBox.Checked[Index] then
  begin
    { Process the path here }
    MsgBox(Format('Processing path %s', [Dirs[Index]]), mbInformation, MB_OK);

    { In your case, you delete the folder }
    DelTree(Dirs[Index], True, True, True);
  end;
end;

上面其实和代码差不多,你在我之前的回答里已经有了

这是同一个概念,我已经在你的另一个问题中向你展示过:Inno Setup - Check if multiple folders exist


如果个别复选框确实需要特殊处理(即它们不代表质量相同的项目列表),正确的方法是在生成它们时记住它们的索引:

if ShouldAddItem1 then
  Item1Index := CheckListBox.AddCheckBox(...)
else
  Item1Index := -1;

if ShouldAddItem2 then
  Item2Index := CheckListBox.AddCheckBox(...)
else
  Item2Index := -1;
if (Item1Index >= 0) and CheckListBox.Checked[Item1Index] then
  { Process item 1 }

if (Item2Index >= 0) and CheckListBox.Checked[Item2Index] then
  { Process item 2 }