我正在使用这个答案强制我自己TPopupMenu通过标准窗口"剪切/复制/粘贴"上下文菜单.问题是我不知道如何布置OO结构来实现这一点.
unit BaseRamEditor.pas
type
{ This will override the default TStringGrid. }
TStringGrid = class(Grids.TStringGrid)
protected
function CreateEditor: TInplaceEdit; override;
end;
TfrmBaseRamEditor = class(TForm)
sgrSync: TStringGrid;
RamEdPopup: TPopupMenu;
procedure MenuItem1Click(Sender: TObject);
implementation
{$R *.dfm}
function TStringGrid.CreateEditor: TInplaceEdit;
{ Use our TPopupMenu instead of Windows default. }
begin
Result := inherited CreateEditor;
// XXX: I don't know how to reference the `RamEdPopup` object that belongs to
// `TfrmBaseRamEditor`. I can't reference the `TfrmBaseRamEditor` instance
// because it hasn't been created yet because it depends on THIS new
// `TStringGrid`.
TMaskEdit(Result).PopupMenu := RamEdPopup;
end;
Run Code Online (Sandbox Code Playgroud)
这是在中RamEdPopup定义的BaseRamEditor.dfm.请注意,OnClick引用一个方法的TfrmBaseRamEditor:
BaseRamEditor.dfm
=================
object frmBaseRamEditor: TfrmBaseRamEditor
object RamEdPopup: TPopupMenu
object MenuItem1: TMenuItem
Caption = 'Diagramm 1'
OnClick = MenuItem1Click
end
end
end
Run Code Online (Sandbox Code Playgroud)
所以概述是:
TfrmBaseRamEditor构造函数依赖于重写TStringGridTStringGrid构造依赖于TPopupMenu的TfrmBaseRamEditor.TPopupMenu指向了方法TfrmBaseRamEditor.我如何解决这个混乱,以便TStringGrid用于frmBaseRamEditor使用TPopupMenu?
使用TStringGrid(TfrmBaseRamEditor)的所有者作为引用并将其类型转换为表单以访问该RamEdPopup对象:
TMaskEdit(Result).PopupMenu := TfrmBaseRamEditor(Self.Owner).RamEdPopup;
Run Code Online (Sandbox Code Playgroud)
如果要在运行时检查强制转换,请使用as内在:
TMaskEdit(Result).PopupMenu := (Self.Owner as TfrmBaseRamEditor).RamEdPopup;
Run Code Online (Sandbox Code Playgroud)
您可以在TStringGrid其中创建其他属性,以便设置编辑器弹出菜单:
TStringGrid = class(Grids.TStringGrid)
protected
FEditorPopup: TPopupMenu;
function CreateEditor: TInplaceEdit; override;
procedure SetEditorPopup(Value: TPopupMenu);
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
published
property EditorPopup: TPopupMenu read FEditorPopup write SetEditorPopup;
end;
function TStringGrid.CreateEditor: TInplaceEdit;
begin
Result := inherited CreateEditor;
TMaskEdit(Result).PopupMenu := FEditorPopup;
end;
procedure TStringGrid.SetEditorPopup(Value: TPopupMenu);
begin
if Value <> FEditorPopup then
begin
if Assigned(FEditorPopup) then FEditorPopup.RemoveFreeNotification(Self);
FEditorPopup := Value;
if Assigned(FEditorPopup) then FEditorPopup.FreeNotification(Self);
if Assigned(InplaceEditor) then TMaskEdit(InplaceEditor).PopupMenu := FEditorPopup;
end;
end;
procedure TStringGrid.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FEditorPopup) then EditorPopup := nil;
end;
Run Code Online (Sandbox Code Playgroud)
由于您正在为默认TStringGrid类创建inplace替换,因此EditorPopup在设计时使用已发布属性和设置的方法可能不适合您,但在用户可以开始使用字符串网格之前,没有什么能阻止您EditorPopup在FormCreate事件中设置属性.