例如,是否可以在运行时使用实例化(有条件地)的子类组件替换和释放TEdit?如果是这样,应该如何以及何时完成?我试图将父设置为nil并在表单构造函数和AfterConstruction方法中调用free(),但在这两种情况下我都遇到了运行时错误。


更具体地说,我遇到了访问冲突错误(EAccessViolation)。看起来Franç ois是正确的,当他说在框架构造中释放组件时,Form控制着内务管理。

有帮助吗?

解决方案

这个更通用的例程可以使用Form或Frame(更新为使用新控件的子类):

function ReplaceControlEx(AControl: TControl; const AControlClass: TControlClass; const ANewName: string; const IsFreed : Boolean = True): TControl;
begin
  if AControl = nil then
  begin
    Result := nil;
    Exit;
  end;
  Result := AControlClass.Create(AControl.Owner);
  CloneProperties(AControl, Result);// copy all properties to new control
  // Result.Left := AControl.Left;   // or copy some properties manually...
  // Result.Top := AControl.Top;
  Result.Name := ANewName;
  Result.Parent := AControl.Parent; // needed for the InsertControl & RemoveControl magic
  if IsFreed then
    FreeAndNil(AControl);
end;

function ReplaceControl(AControl: TControl; const ANewName: string; const IsFreed : Boolean = True): TControl;
begin
  if AControl = nil then
    Result := nil
  else
    Result := ReplaceControlEx(AControl, TControlClass(AControl.ClassType), ANewName, IsFreed);
end;

使用此例程将属性传递给新控件

procedure CloneProperties(const Source: TControl; const Dest: TControl);
var
  ms: TMemoryStream;
  OldName: string;
begin
  OldName := Source.Name;
  Source.Name := ''; // needed to avoid Name collision
  try
    ms := TMemoryStream.Create;
    try
      ms.WriteComponent(Source);
      ms.Position := 0;
      ms.ReadComponent(Dest);
    finally
      ms.Free;
    end;
  finally
    Source.Name := OldName;
  end;
end;

使用它像:

procedure TFrame1.AfterConstruction;
var
  I: Integer;
  NewEdit: TMyEdit;
begin
  inherited;
  NewEdit := ReplaceControlEx(Edit1, TMyEdit, 'Edit2') as TMyEdit;
  if Assigned(NewEdit) then
  begin
    NewEdit.Text := 'My Brand New Edit';
    NewEdit.Author := 'Myself';
  end;
  for I:=0 to ControlCount-1 do
  begin
    ShowMessage(Controls[I].Name);
  end;
end;

注意:如果您在框架的AfterConstruction中执行此操作,请注意托管表单构造尚未完成。
释放控件可能会导致很多问题,因为你搞乱了Form控件的内务管理 如果您尝试阅读ShowMessage中显示的新编辑标题,请查看您获得的内容...
在这种情况下,您会想要使用
  ... ReplaceControl(Edit1,'Edit2', False
然后做一个
  ... FreeAndNil(EDIT1)点击 后面。

其他提示

您必须调用TEdit父级的RemoveControl才能删除该控件。使用InsertControl添加新控件。

var Edit2: TEdit;
begin
  Edit2 := TEdit.Create(self);
  Edit2.Left := Edit1.Left;
  Edit2.Top := Edit2.Top;
  Edit1.Parent.Insertcontrol(Edit2);
  TWinControl(Edit1.parent).RemoveControl(Edit1);
  Edit1.Free;
end;

将TEdit.Create替换为您要使用的类,并复制您需要的所有属性,就像我使用Left和Top一样。

您实际上可以使用RTTI(在TypInfo单元中查看)来克隆所有匹配的属性。我曾经为此写过代码,但我现在找不到它。我会继续寻找。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top