Setting style to Menu items

Check the below sample. Click on the button and see the popup Menu. You will see each menu item in different color. This is because a style is set for the menu items at the Menu item level and not at the Menu level. So if you have a requirement to set different style to each menu item, then this article is for you.

Of course this is a very simple solution. Lets see how to do this.

Step 1: First step is to create your custom item renderer. Check below - I am creating "CustomMenuItemRenderer" that extends "MenuItemRenderer". "MenuItemRenderer" is the itemRenderer used by Menu if you dont set any custom itemRenderer. Just override the updateDisplayList(...) function set the style of the Menu items in this function. So the main logic as shown below is "this.styleName = ValueObject(;" of updateDisplayList(...) function. Here I am getting the styleName from the Menu item that is an item in the dataProvider and setting it as style of the element. I am passing the styleName of each Menu item as a field/property of that item. ValueObject is a the object used as MenuItem and it contains "styleName" property. I created two styles - menuOddStyle and menuEvenStyle and passing the same as styleName through ValueObject. You can download the complete source code at the end of this article.

package com.jusfortechies.controls
   import mx.controls.menuClasses.MenuItemRenderer;
   public class CustomMenuItemRenderer extends MenuItemRenderer
      override protected function updateDisplayList(unscaledWidth:Number,
                                             unscaledHeight:Number):void {

         //Get the style name from Menu VO and set to the menu item	
         this.styleName = ValueObject(;
         super.updateDisplayList(unscaledWidth, unscaledHeight);

Step 2: Second step is just using the custom itemrenderer created above by setting it as itemRenderer to Menu. Now you can see different style applied to different menu items. If you check below piece of code, I am passing styleName for each element by setting the "styleName" property of the VO I created and used the same to set the style of the element.

<?xml version="1.0"?>
<mx:Application xmlns:mx="" 

   <mx:Style source="assets/main.css" />
         private var myMenuData:ArrayCollection = new ArrayCollection();

         // Create and display the Menu control.
         private function createAndShow():void {
            var myMenu:Menu = Menu.createMenu(null, myMenuData, false);
            myMenu.itemRenderer = new ClassFactory(CustomMenuItemRenderer);
         public function init():void {
            myMenuData.addItem(new ValueObject("MA", "MenuItem A", "menuOddItem"));

      <mx:Button id="myButton" initialize="init()" label="Open Menu" click="createAndShow();"/>

Dont forget to set CSS file using "<mx:Style source="assets/main.css" />"

You can download the example source code here.

Download the example code.

blog comments powered by Disqus