Thursday, December 6, 2012

How to add a data driven background colour to spark Datagrid

Here is how one would go about adding a data-driven row background colour to spark DataGrid.

Spark DG defines a rowBackground property, an IGridVisualElement, called to draw each row default's background. That is usually null and gives you a white background.

You can easily override it in mxml, with something like this:

<flex44d:FLEX44DNewDataGrid blah...>
<flex44d:rowBackground>
<fx:Component>
<s:Rect implements="spark.components.gridClasses.IGridVisualElement" width="100%" height="100%">
<fx:Script>
<![CDATA[
import spark.components.DataGrid;
import spark.components.Grid;
/**
 * @private
 */
public function prepareGridVisualElement(grid:Grid, rowIndex:int, columnIndex:int):void
{
if (!grid.dataProvider || rowIndex >= grid.dataProvider.length)
rowBackgroundFillColor.color = 0xffffff;
else {
rowBackgroundFillColor.color = outerDocument.rowColorFunction(grid.dataProvider.getItemAt(rowIndex));
}
]]>
</fx:Script>  
<s:fill>
<!--- @private -->   
<s:SolidColor id="rowBackgroundFillColor"/>
</s:fill>
</s:Rect>
</fx:Component>
</flex44d:rowBackground>
</flex44d:FLEX44DNewDataGrid>


Your rowColorFunction should take the grid data as a parameter and return a uint for the background color to draw. Somewhat like this:


 
public function rowColorFunction(data:*):uint
{
if (!data) return 0xffffff; // no data, leave blank, or maybe some other default value
........
return ....;
}

No comments:

Post a Comment