Creating Properties for Subcomponents

From RAD Studio
Jump to: navigation, search

Go Up to Creating properties Index

By default, when a property's value is another component, you assign a value to that property by adding an instance of the other component to the form or data module and then assigning that component as the value of the property. However, it is also possible for your component to create its own instance of the object that implements the property value. Such a dedicated component is called a subcomponent.

Subcomponents can be any persistent object (any descendant of TPersistent). Unlike separate components that happen to be assigned as the value of a property, the published properties of subcomponents are saved with the component that creates them. In order for this to work, however, the following conditions must be met:

  • The Owner of the subcomponent must be the component that creates it and uses it as the value of a published property. For subcomponents that are descendants of TComponent, you can accomplish this by setting the Owner property of the subcomponent. For other subcomponents, you must override the GetOwner method of the persistent object so that it returns the creating component.
  • If the subcomponent is a descendant of TComponent, it must indicate that it is a subcomponent by calling the SetSubComponent method. Typically, this call is made either by the owner when it creates the subcomponent or by the constructor of the subcomponent.

Note: When a component that has subcomponents is streamed, the subcomponents will have their csLoading flag set and their Loaded method called. This can create a complication for any subcomponent properties that are writable. If you allow your subcomponent property to be assigned to an external component reference, then you cannot free your subcomponent until it's owner's Loaded method is called. Otherwise, the streaming system will attempt to call the subcomponent's Loaded method after the subcomponent has been freed.

Typically, properties whose values are subcomponents are read-only. If you allow a property whose value is a subcomponent to be changed, the property setter must free the subcomponent when another component is assigned as the property value. In addition, the component often re-instantiates its subcomponent when the property is set to nil. Otherwise, once the property is changed to another component, the subcomponent can never be restored at design time.

Note that the property setter above called the FreeNotification method of the component that is set as the property value. This call ensures that the component that is the value of the property sends a notification if it is about to be destroyed. It sends this notification by calling the Notification method. You handle this call by overriding the Notification method.

See Also