Determining if a check box menu item is toggled in a Flex PopUpButton control’s pop up menu

The following example shows you how you can determine if a check box menu item in a Flex PopUpButton control was checked or not by using the change event on the pop up menu along with the dataDescriptor property and isToggled() method.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/02/11/determining-if-a-check-box-menu-item-is-toggled-in-a-flex-popupbutton-controls-pop-up-menu/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="top"
        backgroundColor="white">

    <mx:Style>
        PopUpButton {
            popUpStyleName: MyCustomPopUpStyleName;
        }

        .MyCustomPopUpStyleName {
            fontWeight: normal;
            textAlign: left;
        }

        .redModal {
            modalTransparencyColor: red;
            modalTransparency: 0.8;
        }

        .greenModal {
            modalTransparencyColor: haloGreen;
            modalTransparency: 0.8;
        }
    </mx:Style>

    <mx:Script>
        <![CDATA[
            import mx.events.MenuEvent;
            import mx.controls.Menu;
            import mx.controls.Alert;

            private var menu:Menu;
            private function init():void {
                menu = new Menu();
                menu.variableRowHeight = true;
                menu.dataProvider = arr;
                menu.addEventListener(MenuEvent.CHANGE, menu_change);
                popUpButton.popUp = menu;
            }

            private function menu_change(evt:MenuEvent):void {
                switch (menu.dataDescriptor.getType(evt.item)) {
                    case "check":
                        if (menu.dataDescriptor.isToggled(evt.item)) {
                            application.styleName = "greenModal";
                            Alert.show("\\"" + evt.item.label + "\\" was checked");
                        } else {
                            application.styleName = "redModal";
                            Alert.show("\\"" + evt.item.label + "\\" was not checked");
                        }
                        break;
                }
            }
        ]]>
    </mx:Script>

    <mx:Array id="arr">
        <mx:Object label="Option 1"
                type="check"
                toggled="true" />
        <mx:Object label="Option 2"
                type="check"
                toggled="true" />
    </mx:Array>

    <mx:PopUpButton id="popUpButton"
            label="Click to open..."
            openAlways="true"
            initialize="init();" />

</mx:Application>

View source is enabled in the following example.

2 thoughts on “Determining if a check box menu item is toggled in a Flex PopUpButton control’s pop up menu

Comments are closed.