Flex中如何动态生成DataGrid以及动态生成表头
在Flex中动态生成表格,并且表格的表头也是动态生成
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="initHandler()"
width="100%" height="100%">
<mx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.events.ListEvent;
import mx.controls.ComboBox;
import mx.controls.DataGrid;
import mx.collections.ArrayCollection;
import mx.controls.dataGridClasses.DataGridColumn;
[Bindable]
//自定义数据源
private var grid:Array = [
{age:'25', sex: "男",name: "张三"},
{age:'22', sex: "女",name: "李四"},
{age:'23', sex: "男",name: "王五"},
{age:'21', sex: "女",name: "赵六"},
{age:'24', sex: "男",name: "钱七"},
{age:'20', sex: "女",name: "魏八"}
];
/*初始化函数*/
private function initHandler():void
{
var gridArray:ArrayCollection = new ArrayCollection(grid);
gridArray.filterFunction;
//自定义DataGrid控件
var dataGrid:DataGrid = new DataGrid();
//X轴坐标
dataGrid.x = 20;
//Y轴坐标
dataGrid.y = 20;
//数据项是否能编辑
dataGrid.editable = false;
//控件宽度
dataGrid.width = 1300;
//控件高度
//dataGrid.height = 600;
//设置表格行数
dataGrid.rowCount = gridArray.length + 1;
//设置控件内容字体大小
dataGrid.setStyle("fontSize", 20);
//设置表头颜色
dataGrid.setStyle("headerColors",[0xB0C4DE,0xB0C4DE]);
//设置字体位置
dataGrid.setStyle("textAlign","center");
//设置样式名
dataGrid.styleName;
// 设置数据源
dataGrid.dataProvider = gridArray;
// 添加监听事件类型与触发函数
dataGrid.addEventListener(ListEvent.ITEM_CLICK, itemClickHandler);
// 添加dataGrid控件
addChild(dataGrid);
//声明一个数组
var columns:Array = new Array();
var column:DataGridColumn;
for ( var i:* in grid[0] ) {
column = new DataGridColumn(i);
columns.push(column);
}
dataGrid.columns = columns;
}
/*事件*/
private function itemClickHandler(event:ListEvent):void
{
trace(event.target);
}
]]>
</mx:Script>
</mx:Application>
2、结果如下图