tags:

views:

7981

answers:

6

OK I have a ComboBox, the dataProvider is an array of objects with label properties that give the ComboBox the list of options.

Is there a way I can have a variable like mySelectedItem, and bind the ComboBox's selectedItem to it so that if it changes, the ComboBox's selectedItem will change to whatever it is?

I hope this makes sense.

Thanks!

+2  A: 

Use an event listener for the Change event and do your processing there.

// update a label item's text with that of the Combobox's selectedItem
private function changeEvt(event:Event):void {
    label.text =event.currentTarget.selectedItem.label + " " + 
}
dirkgently
+9  A: 

Yes, ComboBox's selectedItem property is bindable.

It would go something like this:

<mx:ComboBox selectedItem="{mySelectedItem}">
</mx:ComboBox>

In your AS:

[Bindable]
var mySelectedItem:Object;

Changes to mySelectedItem should show up in ComboBox. You may get errors if the item referenced by mySelectedItem does not exist in the ComboBox's dataProvider.

CookieOfFortune
+2  A: 

On the surface, it's as simple as:

<mx:ComboBox id="myComboBox"
   dataProvider="{myDataProvider}"
   selectedItem="{defaultItem}"/>

When you set defaultItem (make sure it is [Bindable]) to one of the items in the data provider, it will update the control.

But there are problems with this approach. Unless currentDefaultItem always changes AFTER myDataProvider, the binding to dataProvider may undo the selection, reverting to the default (first item in the list).

One way around this is to force selectedItem to be rebound after dataProvider, by including dataProvider in the call providing the selectedItem.

<mx:ComboBox id="myComboBox"
   dataProvider="{myDataProvider}"
   selectedItem="{getSelectedItem(myComboBox.dataProvider, defaultItem)}"/>

What this does is ensure selectedItem will be rebound when either currentDefaultItem changes, or after the dataProvider changes. I'd be interested in other solutions myself.

Chris Thornhill
A: 

I know this is how its described in the documentation. As in a change to the selectedItem will fire the change listener. However for me, this does not happen. Anyone else encounter the same behavior?

A: 

This looks like a great approach: make the value attribute writeable: http://flex.sys-con.com/node/312098

datico
A: 

or, you could do something like this if you don't mind extending ComboBox; This is pseudocode (sorry, identification of matches depends on the object type) - but you get the idea...

public class IndexRetainingComboBox extends ComboBox 
{
    public function IndexRetainingComboBox()
    {
        super();
    }

    override public function set dataProvider(value:Object):void
    {
        var originalSelection:Object = this.selectedItem;
        super.dataProvider = value;
        var newIdx:uint = [find originalSelection idx in combobox or return 0 ]
        this.selectedIndex = newIdx;
    }
}
Cyrus Amiri