Adobe Flex 3 Help

Defining native menus declaratively

Coding the properties of a menu and menu items can be a bit tedious. However, since menus have a natural hierarchical structure, it is straightforward to write a function that creates a menu using an XML-formatted definition.

The following class extends NativeMenu, taking an XML object in its constructor, to do just that:

package
{
    import flash.display.NativeMenu;
    import flash.display.NativeMenuItem;
    import flash.events.Event;

    public class DeclarativeMenu extends NativeMenu
    {
        public function DeclarativeMenu(XMLMenuDefinition:XML):void
        {
            super();
            addChildrenToMenu(this, XMLMenuDefinition.children());
        }
        
        private function addChildrenToMenu(menu:NativeMenu,
                                children:XMLList):NativeMenuItem
        {
            var menuItem:NativeMenuItem;
            var submenu:NativeMenu;
            
            for each (var child:XML in children)
            {
                if (String(child.@label).length > 0)
                {
                    menuItem = new NativeMenuItem(child.@label);
                    menuItem.name = child.name();
                }
                else
                {
                    menuItem = new NativeMenuItem(child.name());
                    menuItem.name = child.name();
                }
                menu.addItem(menuItem);
                if (child.children().length() > 0)
                {
                    menuItem.submenu = new NativeMenu();
                    addChildrenToMenu(menuItem.submenu,child.children());
                }
            }
            return menuItem;
        }
    } //End class
} //End package

To create a menu with this class, pass an XML menu definition as follows:

var menuDefinition:XML = 
    <root> 
        <FileMenu label='File'>
            <NewMenu label='New'>
                <NewTextFile label='Text file'/>
                <NewFolder label='Folder'/>
                <NewProject label='Project'/>
            </NewMenu>
            <OpenCommand label='Open'/>
            <SaveCommand label='Save'/>
        </FileMenu>
        <EditMenu label='Edit'> 
            <CutCommand label='Cut'/> 
            <CopyCommand label='Copy'/>
            <PasteCommand label='Paste'/> 
        </EditMenu>
        <FoodItems label='Food Items'>
            <Jellyfish/> 
            <Tripe/> 
            <Gizzard/> 
        </FoodItems>
    </root>;
var test:DeclarativeMenu = new DeclarativeMenu(menuDefinition);

To listen for menu events, you could listen at the root menu level and use the event.target.name property to detect which command was selected. You could also look up items in the menu by name and add individual event listeners.