好的我有一個ComboBox,dataProvider是一個帶有標籤屬性的對象數組,這些對象爲ComboBox提供了選項列表。Flex:有沒有辦法將ComboBox的selectedItem綁定到變量上?
有沒有辦法讓我有一個像mySelectedItem這樣的變量,並將ComboBox的selectedItem綁定到它,這樣如果它發生變化,ComboBox的selectedItem會變成它是什麼?
我希望這是有道理的。
謝謝!
好的我有一個ComboBox,dataProvider是一個帶有標籤屬性的對象數組,這些對象爲ComboBox提供了選項列表。Flex:有沒有辦法將ComboBox的selectedItem綁定到變量上?
有沒有辦法讓我有一個像mySelectedItem這樣的變量,並將ComboBox的selectedItem綁定到它,這樣如果它發生變化,ComboBox的selectedItem會變成它是什麼?
我希望這是有道理的。
謝謝!
是的,ComboBox的selectedItem屬性是可綁定的。
它會去是這樣的:
<mx:ComboBox selectedItem="{mySelectedItem}">
</mx:ComboBox>
在您的AS:
[Bindable]
var mySelectedItem:Object;
更改mySelectedItem應該在組合框顯示。如果在ComboBox的dataProvider中不存在由mySelectedItem引用的項目,則可能會出錯。
使用Change
事件的事件偵聽器並在那裏處理。
// 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 + " " +
}
從表面上看,它是那樣簡單:
<mx:ComboBox id="myComboBox"
dataProvider="{myDataProvider}"
selectedItem="{defaultItem}"/>
當您設置defaultItem(確保它是[綁定])在數據提供者的項目之一,它會更新該控件。
但是這種方法存在問題。除非currentDefaultItem始終在myDataProvider之後更改,否則與dataProvider的綁定可能會撤消選擇,恢復爲默認值(列表中的第一項)。
解決此問題的一個方法是,通過在提供selectedItem的調用中包含dataProvider,強制selectedItem在dataProvider之後重新啓動。
<mx:ComboBox id="myComboBox"
dataProvider="{myDataProvider}"
selectedItem="{getSelectedItem(myComboBox.dataProvider, defaultItem)}"/>
這樣做是爲了確保當currentDefaultItem更改或dataProvider更改後,selectedItem會被反彈。我自己會對其他解決方案感興趣。
我知道這是如何在文檔中描述的。 由於對selectedItem的更改將觸發更改偵聽器。但對我而言,這並未發生。其他人遇到相同的行爲?
這看起來像一個巨大的辦法:讓屬性值可寫: http://flex.sys-con.com/node/312098
或者,你可以做這樣的事情,如果你不介意延長組合框; 這是僞代碼(對不起,匹配識別取決於對象類型) - 但你的想法...
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;
}
}
我用的selectedIndex注意到了這一點。 – Panzercrisis 2012-11-02 13:01:14