[Flex] One labelfunction for multiple datagridcolumns
On March 27, 2007, Flash / Flex - 2 CommentsThe labelfunction of a listbased component is nice, but a bit limited.
For instance, you have to specify the (data)fieldname inside the function, which makes it impossible to use it for other columns. Wouldn’t it be nice if you could write one labelfunction for all your columns? I thought it would.
In order to accomplish this, I needed to have the columndata inside the labelFunction. At first, I was thinking of extending the labelFunction, but that wouldn’t help me much, because Flex was still sending only the original data and not the columndata. So I went deeper in the component, searching for the function responsible for calling the labelFunction.
I discovered it was the labelFunction. Luckily it was a public function so I could override it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package nl.ik.components { import mx.controls.DataGrid; public class IKDataGrid extends DataGrid { override public function itemToLabel(data:Object):String { //Check if it has a labelfunction if (data != null && labelFunction != null) { return labelFunction(data, iterator.current.dataField); } //Resume normal behaviour return super.itemToLabel(data); } } } |
The iterator is an internal object which loops over all the data. The current specifies the currentnode and the datafield is a property I set in mxml to identify the column.
<?xml version="1.0" encoding="utf-8"?> <mx:VBox width="100%" height="100%" xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:components="nl.ik.components.*"> <components:IKDataGrid dataProvider="{Model.getInstance().itemVO.items}"> <components:columns> <mx:DataGridColumn headerText="Label" dataField="label" labelFunction="gridLabel" /> <mx:DataGridColumn headerText="Title" dataField="title" labelFunction="gridLabel" /> <mx:DataGridColumn headerText="Creation date" dataField="creationdate" labelFunction="gridLabel" /> </components:columns> </components:IKDataGrid> <mx:Script> <![CDATA[ public function gridLabel(data:Object, column:Object):String { //column holds all the properties of the current column. In this example it just returns te appropriate value, //but imagine what you can do with this function! return data[column.dataField]; } ]]> </mx:Script> </mx:VBox> |
What others have to say:
ja…. inderdaad!
Great job – simple and very efficient!
Leave a Reply