20070524

Single ItemRenderer for Multiple Columns in a DataGrid

Many a times we have similar columns in a datagrid and are required to be rendered in a similar manner with only little variations like formatting of the column. It is redundant in such a case to write a separate ItemRenderer per column. A better approach would be to write single ItemRenderer and pass properties to the ItemRenderer to identify a particular column.


This can be achieved by settings the ItemRenderer to column using Actionscript.
The catch is to pass properties to ItemRenderer using ClassFactory.properties method.

http://livedocs.adobe.com/flex/2/langref/mx/core/ClassFactory.html

Here's the sample code:



var colRendererFactory:ClassFactory = new ClassFactory(columnRendererClass);
colRendererFactory.properties = {columnName:"mycol1"};
column1.itemRenderer = colRendererFactory

var colRendererFactory2:ClassFactory = new ClassFactory(columnRendererClass);
colRendererFactory2.properties = {columnName:"mycol2"};
column2.itemRenderer = colRendererFactory2;


This way you can have the same itemrenderer for multiple columns and can do different styling for each column based on the properties passed.

1 comment:

Bhuvan Gupta said...

Few more things to note:
1. One can although access the column information in the following way inside your ItemRenderer

var dg:DataGrid = (listData) ? DataGrid(listData.owner) : null;

var column:DataGridColumn = (dg) ? dg.columns[listData.columnIndex] as DataGridColumn : null;

2. In order to access the listData, your renderer needs to implement IDropInListItemRenderer. See this link:

http://livedocs.adobe.com/flex/201/html/cellrenderer_072_15.html