Search code examples
delphipropertiescomponentsdelphi-7

Maintain my component's properties when they are changed?


I have a custom component with some published properties which have been used for a while in many projects. I want to make some particular changes to this component which requires removing these old properties and replacing them with new ones. Or otherwise, I'm not necessarily removing the properties, but let's say I just simply change the name of a property from PropName to MyPropName instead. Well, the next time any project using that component is opened, it will not be able to find PropName.

Is there any way to automate conversion of this? Or is this something people will have to do manually? What would be the proper way to maintain component property values when the names of those properties are changed?

And I mean just in the DFM code, not necessarily inside the source code.


Solution

  • You can use the DefineProperties extension point to help migrate your .dfm files.

    type
      TMyComponent = class(...)
      private
        procedure ReadPropName(Reader: TReader);
      protected
        procedure DefineProperties(Filer: TFiler); override;
      published
        property MyPropName: string read ... write ...;
      end;
    
    procedure TMyComponent.DefineProperties(Filer: TFiler);
    begin
      inherited;
      Filer.DefineProperty('PropName', ReadPropName, nil, False);
    end;
    
    procedure TMyComponent.ReadPropName(Reader: TReader);
    begin
      MyPropName := Reader.ReadString;
    end;
    

    This will allow your new component to read in old .dfm files with the old property name. When the .dfm file is written again, the new property name will be used.

    Note that such a technique results in the component being able to read .dfm files containing either the old property name or the new property name so you can migrate in a gradual fashion if you wish. Once you have migrated all your .dfm files then it would be worth removing such code for the sake of tidiness.

    The Delphi documentation covers this subject area, albeit from a slightly different perspective, in the Storing and Loading Unpublished Properties section of the Component Writer's Guide.