Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flex: Is there a way to bind ComboBox's selectedItem to a variable?

Tags:

apache-flex

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!

like image 879
JD Isaacks Avatar asked Apr 29 '09 18:04

JD Isaacks


3 Answers

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.

like image 95
CookieOfFortune Avatar answered Oct 13 '22 14:10

CookieOfFortune


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.

like image 39
Chris Thornhill Avatar answered Oct 13 '22 15:10

Chris Thornhill


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 + " " + 
}
like image 33
dirkgently Avatar answered Oct 13 '22 14:10

dirkgently