【转】flex中的labelFunction(combox和dataGrid)
Flex中,对于显示一个字段,只需要指定对应字段属性给labelField即可,当需要上述所需要的功能的时候就得做个转换了,在Flex的基于List的组件都有一个labelFunction方法能很简单指定所需要显示的内容。
如有这么一个例子,有一个对象他包含一个name和age,现在需要一个ComboBox显示为:“name,age”,下面看例子代码:
1 <?xml version="1.0" encoding="utf-8"?> 2 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" 3 creationComplete="init()" backgroundColor="white"> 4 <mx:Script> 5 <![CDATA[ 6 7 [Bindable] 8 private var cbxDataProvider:Array; 9 10 private function init():void 11 { 12 cbxDataProvider = [ 13 {name:"kissjava", age:"100"}, 14 {name:"rocky", age:"88"}, 15 {name:"jiang", age:"99"} 16 ]; 17 } 18 19 private function cbxDisplayFunction(data:Object):String 20 { 21 var label:String = ""; 22 if(data.hasOwnProperty("name")){ 23 label += data.name + ","; 24 } 25 if(data.hasOwnProperty("age")){ 26 label += data.age; 27 } 28 29 return label; 30 } 31 ]]> 32 </mx:Script> 33 <mx:Text id="text" x="30" y="30" text="这是labelFunction的测试例子"/> 34 <mx:ComboBox id="cbx" labelFunction="cbxDisplayFunction" 35 dataProvider="{cbxDataProvider}" x="30" y="60"/> 36 </mx:Application>
在dataGrid中,稍有不一样,参数(item:Object, column:DataGridColumn)是必须的,如果有多列,item.xxx代表那一列,dataField的属性也是需要的。返回值是String。
1 <?xml version="1.0" encoding="utf-8"?> 2 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"> 3 <mx:Script> 4 <![CDATA[ 5 [Bindable] 6 public var myDataProvider:Array = [ 125000000.99, 7 1700000000.01, 8 984561321483.56, 9 0.99, 10 5.75, 11 31400000000.01]; 12 13 public function myLabelFunction(item:Object, column:DataGridColumn):String 14 { 15 var amount:String = item.toString(); //若有多列,这里需要item.xxx 16 var dollars:String = amount.split(".")[0]; 17 var dollarDigitCount:Number = dollars.toString().length; 18 19 var value:String; 20 21 if (dollarDigitCount >= 7 && dollarDigitCount <= 9) 22 { 23 value = dollars.slice(0, -6) + " Million"; 24 } 25 else if (dollarDigitCount >= 10 && dollarDigitCount <= 12) 26 { 27 value = dollars.slice(0, -9) + " Billion"; 28 } 29 else if (dollarDigitCount >= 13) 30 { 31 value = dollars.slice(0, -12) + " Trillion"; 32 } 33 else 34 { 35 value = item.toString(); 36 } 37 38 return "$" + value; 39 } 40 ]]> 41 </mx:Script> 42 43 <mx:DataGrid id="dg" dataProvider="{myDataProvider}" > 44 <mx:columns> 45 <mx:DataGridColumn headerText="Click To Sort" labelFunction="myLabelFunction"/> 46 <!-- 这里没有dataField是因为只有一列 --> 47 </mx:columns> 48 </mx:DataGrid> 49 50 <mx:TextInput id="textInput" text="{dg.selectedItem}"/> 51 52 </mx:Application>