Passionate Development From Journeyman to Master

Alternating Row Colors For Flex Spark Datagrid

The previous Flex datagrid (MX) - has a parameter that you can supply for the alternating row colors For example:

<mx:DataGrid alternatingItemColors="[#EEE,#FFF]">
  ...
  </mx:DataGrid>

Nice and simple.

Not so, with the new Spark datagrid - it’s a little bit more convoluted to achieve the same Spark datagrid. Not only that, there is a little gotcha that will leave you scratching your head for a long time on why it isn’t working out of the box. I have scratched my head long enough, so you don’t have to!

Alright first of all, I’ve tested this on Flex SDK 4.6.

AlternatingRowColorsBackground

Spark datagrid has this property called the alternatingRowColorsBackground. And so you’d expect this will get you what you want:

<s:DataGrid alternatingRowColorsBackground="[#EEE,#FFF]">
  ...
  </s:DataGrid>

Ehm, not quite. Apparently you can’t just supply the colors to the grid ala the mx counterpart, instead you’re expected to create a skin for the alternating colors, as mentioned on the docs:

If you want to change how this style is rendered, replace the alternatingRowColorsBackground skin part in the DataGridSkin class. If you want to specify the background for each row, then initialize the rowBackground skin part directly.

The Solution

And so the proper solution is to create a custom skin for the grid. This is a sound idea if you are customizing other part of the grid or if you want to share the effect on other grids on your application. But if you only have one grid in your application - this approach seem to introduce a whole lot of codes for a simple need. But anyway..

Create a custom skin and override the prepareGridVisualElement method like the example below:

public function prepareGridVisualElement(grid:Grid, rowIndex:int, columnIndex:int):void {
    const dataGrid:DataGrid = grid.dataGrid;
    if (!dataGrid) return;

    const colors:Array = [0xFFFFFF, 0xEEFAFF];
    if (colors && (colors.length > 0)) {
      dataGrid.styleManager.getColorNames(colors); // lazily replace color names with ints
      rowBackgroundFillColor.color = colors[rowIndex % colors.length];
    } else {
      // This should be the same as bgFill.color.
      rowBackgroundFillColor.color = Colors.WHITE;
    }
  }

Now this is the part that I admit, I don’t quite understand. You need provide an initializer to the grid as the code below show:

<s:DataGrid id="dataGrid"
				skinClass="styles.customDataGridSkin"
				initialize="dataGrid.grid.rowBackground = dataGrid.alternatingRowColorsBackground">
  ...
  </s:DataGrid>

That initialize line took me a long time to find - wasn’t described anywhere on the docs. I found it from this post in a Adobe forum thread.

And so you have it…

flex

Comments