1.创建一个扩展自 mx.controls.DataGrid 的类。这个类可以是MXML文件或者ActionScript文件,你可以根据自己的习惯创建。
2.覆写 protected 方法 drawRowBackground :
{
// 这里可以做一些对数据的判断,然后更改相应的颜色。比如color = 0xFF0000;
// 调用super函数来执行更改。
super.drawRowBackground(s,rowIndex,y,height,color,dataIndex);
}
3.在你的程序中用你新建的类替代 <mx: DataGrid>。
在 drawRowBackground 方法中你可以对数据做一些判断。dataIndex 参数可以用来查看dataProvider 中某一行所显示的数据。例如:假设你想要将数值大于1000的行都显示为绿色:
if( item.quantity > 1000 ) color = 0x00FF00;
具体例子:
首先写自定义类 继承自DataGrid
package BaseUI
{
import flash.display.Sprite;
import mx.controls.DataGrid;
public class CustomerDataGrid extends DataGrid
{
private var _rowColorFunction:Function; //用于在外部能通过指定一个方法 去实现改变列的背景色
public function CustomerDataGrid()
{
super();
}
public function set rowColorFunction(f:Function):void
{
this._rowColorFunction = f;
}
public function get rowColorFunction():Function
{
return this._rowColorFunction;
}
//复写该方法
override protected function drawRowBackground(s:Sprite,rowIndex:int,y:Number, height:Number, color:uint, dataIndex:int):void
{
if( this.rowColorFunction != null ){
if( dataIndex < this.dataProvider.length ){
var item:Object = this.dataProvider.getItemAt(dataIndex);
color = this.rowColorFunction.call(this, item, color);
}
}
super.drawRowBackground(s, rowIndex, y, height, color, dataIndex);
}
}
}
之后在外面使用该自定义控件,注意要为该控件指定rowColorFunction
<BaseUI:CustomerDataGrid
id="dgRain"
width="100%"
height="100%"
dataProvider="{ac}"
borderVisible="false"
click="cli(event)"
rowColorFunction="colorFunction" //指定了改变颜色的方法
>
<BaseUI:columns>
<mx:DataGridColumn dataField="waid"
headerText="预警编号" visible="false"/>
<mx:DataGridColumn dataField="wanm"
headerText="预警名称"/>
<mx:DataGridColumn dataField="stcd"
headerText="测站编号" visible="false"/>
<mx:DataGridColumn dataField="STNM"
headerText="测站名称"/>
<mx:DataGridColumn dataField="stid"
headerText="状态" labelFunction="stateFunction"/>
<mx:DataGridColumn dataField=""
headerText="操作" itemRenderer="view.ssjk.ui.SsjkRainItemRender"/>
</BaseUI:columns>
</BaseUI:CustomerDataGrid>
//改变颜色方法
private function colorFunction(item:Object, color:uint):uint
{
switch(item.stid)
{
case 0:
break;
case 1:
color=0xF10026;
break;
case 2:
color=0x26972d;
break;
case 3:
color=0xFFDF00;
break;
case 4:
color=0xFFDF00;
break;
case 5:
color=0xFFDF00;
break;
case 6:
color=0xFFDF00;
break;
case 7:
color=0xFFDF00;
break;
}
return color;
}
下面为效果图~~