EConvertError when assigning an instance of TMenuItem to another

In one of my applications, the dropdown menu and popup menu have some menu items (which are built dynamically), so I thought that I could add an instance of TMenuItem to both menus using this code:

 MI := TMenuItem.Create(nil); { set MI action } DropDownMenu.Add(MI); PopupMenu.Items.Add(MI); 

Wrong. I received an EMenuError message with a Menu message twice. Rational, so I changed my code to two instances of my menu item using this code:

 MI := TMenuItem.Create(nil); { set MI action } PopupMenu.CreateMenuItem.Assign(MI); DropDownMenu.Add(MI); 

Wrong. I get an EConvertError with this message: Unable to assign TMenuItem TMenuItem. Am I doing something wrong?

+4
source share
1 answer

This is a common error message. Most visual components in Delphi do not override TPersistent.Assign . When this method is not overridden, a default implementation is implemented that simply throws an exception and populates the class names of the source and target objects. I think that it remained unfulfilled, because it is not clear which properties should be copied, in general, so the solution remains for you as a programmer.

If you create a descendant of the classes you use, you can implement Assign or AssignTo to copy all the properties you want, but it may not be worth the effort. Instead, it might be easiest to write a function that does the copying:

 procedure AssignMenuItem(Target, Source: TMenuItem); 

For menus and buttons, the best solution is to use TAction . Assign an action title, icon, help identifier, and event handlers, and then associate this action with all buttons and menu items that should have the same behavior. All of them can participate in the same action. Changes to the properties of an action at runtime will be automatically displayed in the corresponding visual controls.

+6
source

All Articles