Yesterday I need a Flex cell renderer that would change the background color based on the value of the cell (for example, green if a positive number and red if negative). Unfortunately, background color is not a style, that would have been the simplest option.
The solution is to use ActionScript drawing APIs, and the following code was given to me by Flex Evangelist Christophe Coenraets. I am posting it here in case anyone else needs it, and so that I’ll have it around when I need it next.
First the renderer:
package {
import mx.controls.Label;
import mx.controls.dataGridClasses.*;
import mx.controls.DataGrid;
import flash.display.Graphics;
public class BackgroundColorRenderer extends Label
{
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
var g:Graphics = graphics;
var grid:DataGrid = DataGrid(DataGridListData(listData).owner);
if (data.balance >= 0)
{
g.beginFill(0x009900);
g.drawRect(0, 0, unscaledWidth, unscaledHeight);
g.endFill();
}
else
{
g.beginFill(0xFF0000);
g.drawRect(0, 0, unscaledWidth, unscaledHeight);
g.endFill();
}
}
}
}
And here is an example of the renderer being used:
Leave a Reply