如何使用操作来确定控件的可见性?

Dav*_*nan 7 delphi

我正在尝试使用操作来控制控件的可见性.我的代码看起来像这样:

Pascal文件

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ActnList, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    ActionList1: TActionList;
    Action1: TAction;
    CheckBox1: TCheckBox;
    procedure Action1Update(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Action1Update(Sender: TObject);
begin
  (Sender as TAction).Visible := CheckBox1.Checked;
end;

end.
Run Code Online (Sandbox Code Playgroud)

表格文件

object Form1: TForm1
  object Button1: TButton
    Left = 8
    Top = 31
    Action = Action1
  end
  object CheckBox1: TCheckBox
    Left = 8
    Top = 8
    Caption = 'CheckBox1'
    Checked = True
    State = cbChecked
  end
  object ActionList1: TActionList
    Left = 128
    Top = 8
    object Action1: TAction
      Caption = 'Action1'
      OnUpdate = Action1Update
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

首次运行表单时,按钮可见,并选中复选框.然后我取消选中复选框,按钮消失.当我重新选中复选框时,该按钮无法重新出现.

我认为这个的原因可以在以下本地函数中找到TCustomForm.UpdateActions:

procedure TraverseClients(Container: TWinControl);
var
  I: Integer;
  Control: TControl;
begin
  if Container.Showing and not (csDesigning in Container.ComponentState) then
    for I := 0 to Container.ControlCount - 1 do
    begin
      Control := Container.Controls[I];
      if (csActionClient in Control.ControlStyle) and Control.Visible then
          Control.InitiateAction;
      if (Control is TWinControl) and (TWinControl(Control).ControlCount > 0) then
        TraverseClients(TWinControl(Control));
    end;
end;
Run Code Online (Sandbox Code Playgroud)

检查Control.Visible似乎阻止我的行动有机会再次更新自己.

我是否正确诊断了该问题?这是设计还是我应该提交质量控制报告?有没有人知道一个解决方法?

Rob*_*edy 8

你的诊断是正确的.自从他们第一次被引入德尔福以来,行动就一直如此.

我希望它是设计的(可能是为了避免过度更新文本和隐形控件的其他视觉方面的优化),但这并不意味着设计是好的.

我能想象的任何解决方法都会涉及你的复选框代码直接操纵受影响的操作,这不是很优雅,因为它不应该知道它可能影响的其他一切 - 这就是OnUpdate事件应该为你做的事情.选中复选框后,调用Action1.Update,或者如果不起作用,则Action1.Visible := True.

您也可以在TActionList.OnUpdate事件中添加动作更新代码.