delphi – 如何使用子属性编写属性?

前端之家收集整理的这篇文章主要介绍了delphi – 如何使用子属性编写属性?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
例如,像Font一样.谁能举一个非常简单的例子?也许只是一个有两个子属性属性

编辑:我的意思是,当我在对象检查器中查看字体时,它有一个小加号,我可以单击以设置字体名称“times new roman”,字体大小“10”等等.如果我使用错误的术语,Sorrry,这就是我所谓的“子属性”.

解决方法

您所要做的就是创建一个新的已发布属性,该属性指向已发布属性的类型.

检查此代码

type
    TCustomType = class(TPersistent) //this type has 3 published properties
    private
      FColor : TColor;
      FHeight: Integer;
      FWidth : Integer;
    public
      procedure Assign(Source: TPersistent); override;
    published
      property Color: TColor read FColor write FColor;
      property Height: Integer read FHeight write FHeight;
      property Width : Integer read FWidth write FWidth;
    end;

    TMyControl = class(TWinControl) 
    private
      FMyProp : TCustomType;
      FColor1 : TColor;
      FColor2 : TColor;
      procedure SetMyProp(AValue: TCustomType);
    public
      constructor Create(AOwner: TComponent); override;
      destructor Destroy; override;
    published
      property MyProp : TCustomType read FMyProp write SetMyProp; //now this property has 3 "sub-properties" (this term does not exist in delphi)
      property Color1 : TColor read FColor1 write FColor1;
      property Color2 : TColor read FColor2 write FColor2;
    end;

  procedure TCustomType.Assign(Source: TPersistent);
  var
    Src: TCustomType;
  begin
    if Source is TCustomType then
    begin
      Src := TCustomType(Source);
      FColor := Src.Color;
      Height := Src.Height;
      FWidth := Src.Width;
    end else
      inherited;
  end;

  constructor TMyControl.Create(AOwner: TComponent);
  begin
    inherited;
    FMyProp := TCustomType.Create;
  end;

  destructor TMyControl.Destroy;
  begin
    FMyProp.Free;
    inherited;
  end;

  procedure TMyControl.SetMyProp(AValue: TCustomType);
  begin
    FMyProp.Assign(AValue);
  end;
原文链接:https://www.f2er.com/delphi/103221.html

猜你在找的Delphi相关文章