2013/07/06

Create an item in a TActionMainMenuBar at runtime

從Reference參考得來的作法,原來之前做出來的Menu無法Enabled的問題在於「沒有把TAction」裝在Menu的第一層,所以就會變成無法啟用,可是這在Design Mode下卻可以正常開啟,果然這其中一定有什麼奧秘是我不知道的啊!

不過,暫時先這樣吧!

底下是失敗的例子:
var
  actItem, actItemA: TActionClientItem;
  Clients: TActionClients;
begin
  Clients := ActionMainMenuBar1.ActionClient.Items;
  actItemA := Clients.Add;
  actItemA.Caption := '&Edit';
  actItem := actItemA.Items.Add;
  actItem.Action := EditCut1;
  actItem.Visible := True;
  actItemA.Visible := True;

正確的作法應該是:
var
  actItem: TActionClientItem;
  actRun,actRun2: TAction;
begin
  actRun := TAction.Create(Self);
  actRun.Name := 'H1';
  actRun.Category := 'HELLO';
  actRun.OnExecute := Action1Execute;
  actRun2 := TAction.Create(Self);
  actRun2.Name := 'H2';
  actRun2.Category := 'HELLO';
  actRun2.OnExecute := Action1Execute;
  with ActionMainMenuBar1.ActionClient.Items.Add do
  begin
    Caption := 'HELLO';
    Action := actRun;  // 每一層一定都要掛載TAction才會把MenuItem Enable
    with Items.Add do
    begin
      Caption := 'HELLO2';
      Action := actRun2;
      with Items.Add do
      begin
        Action := actRun;
      end;
    end;
    Visible := True;
  end;


Reference: Delphi Knowledge Base: Create an item in a TActionMainMenuBar at runtime

沒有留言:

張貼留言