title: Dynamically creating a sub-menu in Delphi
body: <p>I have a popup menu and I want one of the items to open a sub-menu with a dynamically created list (it's a list of user defined flags). Here's how I'm creating the menu items (<code>FlagAs</code> is the menu item I want to attach the sub-menu to):</p>
  
  <pre><code>lNewMenuItems: array[0..flagCount] of tMenuItem;
  
  for I := 0 to flagCount do
  begin
    { Create a new menu item }
    lNewMenuItems[I] := tMenuItem.Create(FlagAs);
    lNewMenuItems[I].Caption := FlagNames[I];
    lNewMenuItems[I].Tag := I; { Tag with the flag number }
    lNewMenuItems[I].OnClick := miFlagClick;
  end;
  
  FlagAs.Add(lNewMenuItems);
  </code></pre>
  
  <p>The <code>miFlagClick</code> handler simply toggles the checked status of its sender:</p>
  
  <pre><code>procedure TMyForm.miFlagClick(Sender: TObject);
  begin
    (Sender as tMenuItem).Checked := not (Sender as tMenuItem).Checked;
  end;
  </code></pre>
  
  <p>The items get added perfectly, but they don't get checked when I click on them. The event handler is being called <strong>EDIT: and Sender is the correct menu item, but the check mark doesn't appear next time I open the menu.</strong></p>
  
  <p>What am I doing wrong? Or am I going about the menu creation in the wrong way? (Note <code>flagCount</code> may change in the future, but is defined as a constant in the code)</p>
  
  <p><strong>EDIT: the above does actually work - see my answer below</strong> </p>