现在的位置: 首页 > 综合 > 正文

动态添加 DataGrid 的列

2013年01月03日 ⁄ 综合 ⁄ 共 1338字 ⁄ 字号 评论关闭

大家都知道在Flex中基本上每一个MXML 标签都对应着一个AS类。所以你既可以用MXML声明组件,也可以使用ActionScript创建,而后一种方法尤为灵活。今天我就遇到了一个需要动态创建DataGrid的程序,经过数次实验之后,终于成功。

1.首先,需要动态创建一个DataGrid。
程序代码
var dg:DataGrid = new DataGrid();
dg.id = “myDG”; // 设定id
dg.width = 400; // 设定宽度
………… // 其它属性
这些写好之后要将其添加到程序的 DisplayList中,这里假设我有一个 id 为 “vb” 的 VBOX 容器,可以这么写:
程序代码
vb.addChild(dg);
写完这些先看看效果吧:
效果如图所示,就这么一个类似面板的东西,里面没有我们通常见到的列表。为什么呢?因为你创建 DataGrid 的时候那些列不是自带的,而是需要另外创建的。那些列是 mx.controls.dataGridClasses.DataGridColumn 的实例,需要另外创建。接下来我们就来创建
2. 创建DataGridColumn。
一般来说,你需要几列就创建几个DataGridColumn。比如:
程序代码
var column1:DataGridColumn = new DataGridColumn();
column1.headerText = “column1″;
……………… // 其它属性的设定
var column2:DataGridColumn = new DataGridColumn();
column2.headerText = “column2″;
……………… // 其它属性的设定
3.将创建的DataGridColumn添加到DataGrid中。
DataGrid有一个属性columns,是一个数组,它包含了DataGrid中所有column实例。
我直接这样添加列:
程序代码
dg.columns.concat(column1);
dg.columns.concat(column2);
然后运行,发现运行结果和没有添加一样!! 怎么会这样呢?语法没有错误啊。再仔细看了帮助中关于DataGrid 的 columns属性介绍,发现这么一段话:
引用内容
If you want to change the set of columns, you must get this array, make modifications to the columns and order of columns in the array, and then assign the new array to the columns property. This is because the DataGrid control returned a new copy of the array of columns and therefore did not notice the changes.
原来你引用这个columns属性的时候并不是引用它本身,而是获得了它的一个新的拷贝,之后你做的所有操作都是在这个拷贝上做得,自然无法影响原来的属性值。改写一下刚才的代码:
程序代码
dg.columns = dg.columns.concat(column1);
dg.columns = dg.columns.concat(column2);

抱歉!评论已关闭.