Reputation:
I am using this example from blog.flexexamples.com.
I have a datagrid and trying to dynamically add button to one of datagrid column. But I want this Button as an ItemRenderer to be written in ActionScript and not MXML.
How can I do that ?
Thanks
Upvotes: 1
Views: 2768
Reputation: 46395
I think this is what you need.
ActionButtonItemRenderer.as :
package
{
import flash.events.MouseEvent;
import mx.controls.Alert;
import mx.controls.Button;
import mx.controls.listClasses.IDropInListItemRenderer;
import mx.controls.listClasses.IListItemRenderer;
import mx.core.IFlexDisplayObject;
public class ActionButtonItemRenderer extends Button implements IFlexDisplayObject, IListItemRenderer, IDropInListItemRenderer
{
public var btn:Button;
public function ActionButtonItemRenderer()
{
super();
btn = new Button();
btn.label = "Take Action";
btn.addEventListener(MouseEvent.CLICK,clickHandler);
btn.visible = btn.includeInLayout = true;
}
override protected function clickHandler(event:MouseEvent):void
{
super.clickHandler(event);
Alert.show("Button clicked");
}
}
}
DynamicDataGridButton.mxml :
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="955" minHeight="600">
<mx:ApplicationControlBar dock="true">
<mx:Button label="Add column" click="init();" />
</mx:ApplicationControlBar>
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var arr:ArrayCollection = new ArrayCollection
(
[
{fname:'A',lname:'B'},
{fname:'C',lname:'B'},
{fname:'D',lname:'B'}
]
);
private function addDataGridColumn(dataField:String):void {
var dgc:DataGridColumn = new DataGridColumn(dataField);
dgc.itemRenderer = new ClassFactory(ActionButtonItemRenderer);
var cols:Array = dg.columns;
cols.push(dgc);
dg.columns = cols;
}
private function init():void {
addDataGridColumn("Details");
}
]]>
</mx:Script>
<mx:DataGrid id="dg" dataProvider="{arr}">
<mx:columns>
<mx:DataGridColumn id="dgc1" dataField="fname" headerText="First Name"
width="75"/>
<mx:DataGridColumn id="dgc2" dataField="lname" headerText=" Last Name"
width="150"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
Upvotes: 2
Reputation: 5706
To dynamically create a button in AS3 syntax you would do this:
var button:Button = new Button();
Then after you've created the button, you can set it's properties like this:
button.label = "Click Me!";
And lastly you would add it to one of your items as such:
var dp:Array = [{label: "Button 1", button: button},{label: "Button 2", button: button}];
myDg.dataProvider = dp;
Then you would feed it to your datagrid that is laid out like this:
<mx:DataGrid id="myDG" variableRowHeight="true">
<mx:columns>
<mx:DataGridColumn dataField="label" headerText="Labels"/>
<mx:DataGridColumn dataField="button" headerText="Buttons"/>
</mx:columns>
</mx:DataGrid>
Not sure if that would actually work though, you may have to have an button itemRenderer on the entire column like this example.
Upvotes: 0