Top | 戻る
ComboBoxを選択しやすくする
画面初期表示はバインディングでささっと書きたいのに、mx:ComboBox 標準のインタフェース
selectedIndex, selectedItem だけではいまいち使えません。
なぜなら多くの場合、コンボボックスに設定したいデータは「○○コード」のような値で持っており、
selectedIndex, selectedItem に指定する値は別途抽出しなければならないからです。
というわけで、コンボボックスに選択したい項目の条件を「○○コード」のような値で指定できるように拡張してみました。
ちょっとした拡張で強力に機能するバインディング、便利です。
ComboBoxEx.as
package {
import mx.controls.ComboBox;
import mx.events.CollectionEvent;
public class ComboBoxEx extends ComboBox {
private var _selectedItemCondition : Object;
public function ComboBoxEx() {
addEventListener(CollectionEvent.COLLECTION_CHANGE, onCollectionChange);
}
public function get selectedItemCondition() : Object {
return _selectedItemCondition;
}
public function set selectedItemCondition(selectedItemCondition : Object) : void {
_selectedItemCondition = selectedItemCondition;
selectByCondition();
}
private function onCollectionChange(e : CollectionEvent) : void {
selectByCondition();
}
public function selectByCondition() : void {
if (collection && selectedItemCondition) {
for (var i : int = 0; i < collection.length; i++) {
var item : Object = collection[i];
var match : Boolean = true;
for (var key : String in selectedItemCondition) {
match &&= (selectedItemCondition[key] == item[key]);
}
if (match) {
selectedIndex = i;
return;
}
}
}
selectedIndex = (collection.length > 0)? 0 : -1;
}
}
}
選択条件のキーとして key1, key2 の2種類用意しました。
selectedItemCondition 属性の二重の波括弧は、外側がバインディング、内側がオブジェクト定義です。
Main.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" xmlns:local="*">
<mx:Script>
<![CDATA[
[Bindable]
private var comboData : Array = [
{label : "default"},
{key1 : "A1", key2 : "B1", label : "A1-B1"},
{key1 : "A1", key2 : "B2", label : "A1-B2"},
{key1 : "A2", key2 : "B1", label : "A2-B1"},
{key1 : "A2", key2 : "B2", label : "A2-B2"}
];
]]>
</mx:Script>
<mx:TextInput id="txt1" text="A1" width="30" toolTip="enter A1 or A2"/>
<mx:TextInput id="txt2" text="B2" width="30" toolTip="enter B1 or B2"/>
<local:ComboBoxEx dataProvider="{comboData}" selectedItemCondition="{{key1 : txt1.text, key2 : txt2.text}}"/>
</mx:Application>
実行結果
Contents Copyright © Kazuhiko Arase