Creating a custom label function on a Flex PopUpMenuButton control

The following example shows how you can use an XML data provider on a PopUpMenuButton in Flex and create a custom label function using the labelFunction property.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/02/21/creating-a-custom-label-function-on-a-flex-popupmenubutton-control/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="top"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            private function getTeams(dp:XML, leagueAbbrev:String, divisionLabel:String):XMLList {
                return dp.league.(@abbrev == leagueAbbrev).division.(@label == divisionLabel).team;
            }

            private function popUpMenuButton_labelFunc(item:Object):String {
                return item.@label + " " + item.@name;
            }
        ]]>
    </mx:Script>

    <mx:XML id="mlb" source="mlb.xml" />

    <mx:XMLListCollection id="mlbXLC"
            source="{getTeams(mlb, 'NL', 'West')}">
        <mx:sort>
            <mx:Sort>
                <mx:fields>
                    <mx:SortField name="@label"
                            caseInsensitive="true" />
                </mx:fields>
            </mx:Sort>
        </mx:sort>
    </mx:XMLListCollection>

    <mx:PopUpMenuButton id="popUpMenuButton"
            dataProvider="{mlbXLC}"
            labelFunction="popUpMenuButton_labelFunc" />

</mx:Application>

View source is enabled in the following example.