在arraycollection中显示行的总和值 - Adob​​e Flex

时间:2017-01-12 15:32:14

标签: actionscript-3 flex flash-builder

我想在arraycollection中显示行的总和值。例如:

Definition     Value
Product 1      20.00
Product 2      50.00
Product 3      30.00

Total          100.00

我有这段代码:

    <mx:DataGrid id="srcgrid">
        <mx:columns>
            <mx:DataGridColumn dataField="Definition"/>
            <mx:DataGridColumn dataField="Value"/>
        </mx:columns>    
    </mx:DataGrid>

    <s:Form>
        <s:FormItem label="Total">
            <s:Label text="{total()}"/>
        </s:FormItem>
    </s:Form>

脚本:

public function total():String {
    var i:Number = 0;
    for each(var obj:Object in ArrayCollection(DataGrid(srcgrid).dataProvider)){
        i = i + obj.Value;
    }

    return i.toString();
}

有什么想法吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

total()内有任何内容之前调用了dataProvider函数 此外,srcgrid.dataProvider可以循环为Object

<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="addInitData(event)">

    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
        <mx:DataGrid id="srcgrid">
        <mx:columns>
            <mx:DataGridColumn dataField="Definition"/>
            <mx:DataGridColumn dataField="Value"/>
        </mx:columns>    
    </mx:DataGrid>

    <s:Form x="250">
        <s:FormItem label="Total">
            <s:Label id="total"/>
        </s:FormItem>
    </s:Form>
    <fx:Script>
        <![CDATA[
            import flash.events.Event;
            import mx.collections.ArrayList;

            private function addInitData(e:Event = null):void{
                var dataProvider:ArrayList = new ArrayList();
                for (var i:int = 0; i < 12; i++){
                    dataProvider.addItem({Definition : 'item_' + i, Value : i});                    
                }
                srcgrid.dataProvider = dataProvider;
                updTotal();
            }

            private function updTotal():void{
                var sum:Number = 0;
                for (var k:String in srcgrid.dataProvider){
                    sum += srcgrid.dataProvider[k]['Value'];
                }
                total.text = sum.toString();
            }
        ]]>
    </fx:Script>
</s:Application>