以DateField在Flex的DataGrid上進行編修

在DataGrid設為editable時進入該欄.會以Text格式去處理編修.但如該欄是個Date 格式時便會出問題,故要用些小技巧來處理才行.我的作法如下:

1.建立一個inline的元件
<mx:Component id=”DateEditor”>
  <mx:DateField formatString=”YYYY/MM/DD”>
   <mx:Script>
    <![CDATA[
     import vo.dm.InvNumber;
     
     override public function set data(value:Object):void{
                  if(listData){
                      this.selectedDate =new Date( value[Object(listData).dataField] );
                } 
        }  
    ]]>
   </mx:Script>
  </mx:DateField>
 </mx:Component>

2.DataGrid上至要有三個event需宣告,及editable設為true
<mx:DataGrid    
    editable=”true” 
     itemEditBegin=”editBegin(event)”
    itemEditEnd=”editEnd(event)”
    itemFocusIn=”itemFocusIn(event)”
     >
3.所用之欄位的itemEditor
<mx:columns>
    <mx:DataGridColumn dataField=”datetimefield_name” labelFunction=”dgDateFunc” width=”100″ itemEditor=”{DateEditor}” />

4.Event handle如下:
   
private function editBegin( event:DataGridEvent ):void {
   var field:String = event.dataField;
   var ADG:DataGrid = event.currentTarget as DataGrid;
   var selectedItem:Object = event.currentTarget.selectedItem;
   //此部份目前沒有特別的處理.
   if (field == “datetimefield_name”) {
     //var ds:String = event.currentTarget.itemEditorInstance
     //event.currentTarget.itemEditorInstance.formatString=”YYYY/MM/DD”;
   }
  }
  
  private function editEnd( event:DataGridEvent ):void {
   
   var field:String = event.dataField;
   var ADG:DataGrid = event.currentTarget as DataGrid;
   var selectedItem:Object = event.currentTarget.selectedItem;

   // 檢查是否修改,如未異動則離開.
   if( ADG.itemEditorInstance is TextInput &&
     ( selectedItem[field] == (ADG as Object).itemEditorInstance.text ) )
       return;

 //在入FocusOut,有時為防制些特例.故我會先移再加入.
   ADG.removeEventListener( DataGridEvent.ITEM_FOCUS_OUT ,itemFocusOut ); 
   ADG.addEventListener( DataGridEvent.ITEM_FOCUS_OUT ,itemFocusOut );
   
    if (field == “datetimefield_name”) {
     var ds:String = event.currentTarget.itemEditorInstance[ADG.columns[event.columnIndex].editorDataField];
     var dateValue:Date = new Date( ds );
      selectedItem[field] = dateValue;

//在此停止掉end edit事件會進行的動作.
      event.preventDefault();
      //清掉DateField元件
      ADG.destroyItemEditor();

     //使顯示為修改後的值
      event.itemRenderer.data  = selectedItem;
            
      return;
     
    }
  }
  
  //修改後的Event
  private function itemFocusOut(e:DataGridEvent):void
  {    
   e.currentTarget.removeEventListener( DataGridEvent.ITEM_FOCUS_OUT ,itemFocusOut );  
   //可在此回存 doUpdate( );   
  }
  
  //for DateField Event
  private function itemFocusIn(event:DataGridEvent):void
  {
   if ( event.itemRenderer is DateField )
      ( event.itemRenderer as DateField).formatString=”YYYY/MM/DD”;
   }

本篇發表於 作法 並標籤為 , , , 。將永久鏈結加入書籤。

發佈留言