本文转载自:http://gis-conquer.blog.sohu.com/159939428.html
发现Flex背景色让行的颜色改变是有些不妥之处,就是在行数较少没有填满当前的DataGrid控件时,就连空行也变了颜色。以下是不本人自定义的一个控件,通过重写drawRowBackground,对绘制的dataIndex进行判断,可以完成设置行的颜色的设置和按值设置指定的颜色:
package widgets.Utility.Control
{
import flash.display.Sprite;
import mx.controls.*;
public class DataGridColored extends DataGrid
{
private var _rowColorFunction:Function;
private var _customed:Boolean;//是否自定义颜色设置
private var _customerColor:uint=0;//自定义颜色
public function DataGridColored()
{
super();
}
public function set rowColorFunction(rowColorFunction:Function):void
{
this._rowColorFunction=rowColorFunction;
}
public function get rowColorFunction():Function
{
return this._rowColorFunction;
}
public function set customed(customed:Boolean):void
{
_customed=customed;
}
public function get customed():Boolean
{
return _customed;
}
public function set customerColor(customerColor:uint):void
{
_customerColor=customerColor;
}
public function get customerColor():uint
{
return _customerColor;
}
override protected function drawRowBackground(s:Sprite, rowIndex:int, y:Number, height:Number, color:uint, dataIndex:int):void
{
if (_customed==true)
{
if (this._rowColorFunction != null)
{
if (dataIndex < this.dataProvider.length)
{
var item:Object=this.dataProvider.getItemAt(dataIndex);//按指定行进行颜色设置
color=this._rowColorFunction.call(this, item, color);
}
}
else
{
if (this._customerColor!=0)
{
if (dataIndex < this.dataProvider.length)
{
color=this._customerColor;
}
}
}
}
super.drawRowBackground(s, rowIndex, y, height, color, dataIndex);
}
}
}
使用时注意两个参数:
customed:Boolean;//是否自定义颜色设置
customerColor:uint=0;//自定义颜色
如:
this.dataGrid.customed=true;
this.dataGrid.customerColor=0x7fceff;
也可直接在MXML进行设置
按值设置指定的颜色需要指定外部回调函数rowColorFunction
如:
在MXML设置:rowColorFunction="rowColorFunction"
下面将column1列值为gisconquer的行颜色设置为0xbeff8e
private function rowColorFunction(item:Object, color:uint):uint
{
if (item['column1'] == "gisconquer") //将column1列值为gisconquer的行颜色设置为0xbeff8e
{
return 0xbeff8e;
}
return color;
}