Flex dynamic ComboBox

By , last updated November 30, 2019

I’ve recently  come to an issue where I needed a ComboBox in Flex with dynamic dataProvider and couldn’t work it around for a while. There is a bug in SDK 3.5 so that a dropdown list in a combobox shows old values after change of dataProvider. To overcome a problem you need to bind the dataProvider.

The way bindings appear is also important: “selectedItem” bindes before “dataProvider” so that “dataProvider” updates before “selectedItem”.

Here is MyComboparent.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas 
    xmlns:mx="http://www.adobe.com/2006/mxml">

    <mx:FormItem id="comboparent">
        <mx:ComboBox id="combo"
            dataProvider="{list1}"
            change="doChange(event)"
            creationComplete="creationComplete(event)"
            tabEnabled="true"/>
    </mx:FormItem>

    <mx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            import mx.binding.utils.ChangeWatcher;
            import mx.utils.StringUtil;
            import mx.controls.ComboBox;
            import mx.binding.utils.BindingUtils;

            private function creationComplete(event:Event):void {
                BindingUtils.bindSetter(workaround, combo, "dataProvider");
            }

            private function doChange(event:Event = null):void {
                combo.dataProvider = list2 as ArrayCollection;
            }

            private function workaround(dataProvider:Object):void {
                if (null == combo) {
                    return;
                }
                if (null == combo.dropdown) {
                    return;
                }
                combo.dropdown.dataProvider = dataProvider;
            }
        ]]>
    </mx:Script>

</mx:Canvas>