In a previous example, “Displaying icons in a Flex PopUpButton control”, we saw how you could add icons to a PopUpButton control’s nested menu using an Array data provider.
The following example shows you how you can add icons to a pop up menu in a PopUpButton control in Flex by specifying the iconField property in the PopUpButton control’s nested Menu control using an XML data provider.
Full code after the jump.
<?xml version="1.0"?>
<!-- http://blog.flexexamples.com/2009/01/20/displaying-icons-in-a-flex-popupbutton-control-redux/ -->
<mx:Application name="PopUpButton_popUp_Menu_iconField_test_2"
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="horizontal"
verticalAlign="top"
backgroundColor="white">
<mx:Script>
<![CDATA[
import mx.controls.Menu;
[Embed("assets/Button.png")]
public const ButtonIcon:Class;
[Embed("assets/ButtonBar.png")]
public const ButtonBarIcon:Class;
[Embed("assets/CheckBox.png")]
public const CheckBoxIcon:Class;
[Embed("assets/ColorPicker.png")]
public const ColorPickerIcon:Class;
[Bindable]
private var menu:Menu;
private function initMenu():void {
menu = new Menu();
menu.dataProvider = xmlList;
menu.labelField = "@label";
menu.iconField = "@icon";
}
]]>
</mx:Script>
<mx:Style>
PopUpButton {
popUpStyleName: myCustomPopUpStyleName;
}
.myCustomPopUpStyleName {
fontWeight: normal;
textAlign: left;
}
</mx:Style>
<mx:XMLList id="xmlList">
<node label="Alert" />
<node label="Button" icon="ButtonIcon" />
<node label="ButtonBar" icon="ButtonBarIcon" />
<node label="CheckBox" icon="CheckBoxIcon" />
<node label="ColorPicker" icon="ColorPickerIcon" />
</mx:XMLList>
<mx:PopUpButton id="popUpButton"
label="Select a control..."
popUp="{menu}"
preinitialize="initMenu();"
creationComplete="popUpButton.open();" />
</mx:Application>

{ 6 comments… read them below or add one }
How do you do this, specify icon when the XML list is specified in an ActionScript class? This class is then specified as the dataProvider via databinding. When I try this for menus the icon is just not displayed (no errors0 and when I do the same for a PopUpMenuButton I get an error saying that cannot parse value of type Class from text ‘@icon’.
Good example. I’m wondering why you use preinitialize instead of initialize in this code?
David Passey,
No reason. The preinitialize event gets run first, but it shouldn’t really matter which event you use (I don’t think — I’m often wrong).
Peter
Is there a way to move the x position of the menu relative to its PopUpButton?
By default, the menu is left aligned with the left edge of the PopUpButton, but my menu has a shadow as part of its borderSkin, so I need to shift the x position of the menu 4 pixels left.
Thanks for your help!
Hi , is there any better way to give popup components to the popupButton ..the problem is when dragging the popup,it seperates from the popup button…Thanks in advance
regards
Reny
@Reny Mohan,
How about setting the
isPopUpproperty to false?Peter