Flex3 自定义ClassFactory,让DataGrid动态改变Button或Image等属性

在Flex的DataGrid中显示按钮Button或者图片Image等,有时会需要Button的标签label,icon是动态改变的,DataGrid也是由Actionscript根据数据库中数据动态生成。这时我们需要自定义ClassFactory来实现这些特性。
package com.yonghong.model
{
import mx.core.ClassFactory;

public class MyClassFactory extends ClassFactory
{
                  //styleCollection represents a collection of style
                  //properties represents a collection of property
private var styleCollection:Object;
public function CMSClassFactory(generator:Class=null,properties:Object=null,styleCollection:Object=null)
{
super(generator);
this.properties=properties;
this.styleCollection=styleCollection;

}

public override  function newInstance():*
    {
        var instance:Object = new generator();

        if (properties != null)
        {
            for (var p:String in properties)
            {
                instance[p] = properties[p];
            }
        }
        if(styleCollection != null){
        for(var s:String in styleCollection){
        instance.setStyle(s,styleCollection[s]);
        }
        }

        return instance;
    }



}
}

以上properties是父类ClassFactory的一个属性。至于动态创建DataGrid,我这里只列出关键代码如下:
//*****************************************
var aColumnDef:ArrayCollection = event.result as ArrayCollection;                 
    var oColumnDef:Object;
    var dg:DataGrid = new DataGrid;
    var dgc:DataGridColumn=new DataGridColumn();
    var aColumnsNew:Array = dg.columns

      
    for (var i:int=0;i<event.result.length;i++)  {                
      oColumnDef = event.result[i];
      dgc = new DataGridColumn();      
      dgc.dataField = oColumnDef.id.datafield;         
     
      //MyButton 是自定义组件,在其中添加了一些事件
      var cf:ClassFactory=new MyClassFactory(MyButton,{label:"ok"},{icon:add});         
      dgc.itemRenderer=cf;                      
      }    
      aColumnsNew.push(dgc)                                      
    }
  
    dg.columns = aColumnsNew;                                     

    dg.editable = true;


    dg.dataProvider = ds;       

//以下是MyButton的定义
package
{
import flash.events.Event;
import flash.events.MouseEvent;
import mx.controls.Alert;
import mx.controls.Button;
public class MyButton extends Button
{

private var currentData:Object;
public function  MyButton()
{
super();
this.addEventListener(MouseEvent.CLICK ,clickHandle)
}

override public function set data(value:Object):void{
this.currentData = value; //保存整行的引用
}

            private function clickHandle(e:Event):void{

//test 是 DataGrid中的一列
Alert.show("xx"+currentData.test);
}                
}

}

希望能帮到一些朋友

你可能感兴趣的:(Flex,Flash,actionscript)