DataGrid中列在可编辑状态下,使用Enter键快速切换焦点的使用方法,包含使用ItemRenderer和ItemEditor的列,需要主要的是,在列中使用了自定义渲染器或者自定义编辑器时,由于焦点切换到自定义渲染器或者自定义编辑器上后,表格焦点会失去(焦点定位到组件上),这时,会无法利用快捷键切换焦点,所以要手动给表格设置焦点。
<?xml version="1.0"?>
<!-- DataGrid control example. -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.events.DataGridEvent;
import mx.utils.StringUtil;
[Bindable]
//定义一个源数组
private var dpFlat:ArrayCollection = new ArrayCollection(
[{name:"苹果",time:"2004-8-3",sprice:10,yprice:8},
{name:"苹果",time:"2011-5-6",sprice:11,yprice:10},
{name:"黄梨",time:"2014-3-5",sprice:6,yprice:4},
{name:"香蕉",time:"2014-2-11",sprice:9,yprice:8},
{name:"桃子",time:"2014-2-23",sprice:5,yprice:3},
{name:"杏子",time:"2014-7-3",sprice:8,yprice:6}
]
);
/**
* 当项目渲染器失去焦点时调度。在下列情况下项目渲染器可能失去焦点:
* 当用户单击 DataGrid 控件中的其它项目或在此控件外部单击时,或使用键盘导航到 DataGrid 控件中的其它项目或导航到该控件外部时。
* 仅当项目可编辑时调度。
**/
protected function dg_itemFocusOutHandler(event:DataGridEvent):void
{
var item:Object = dg.selectedItem;
showLabel.text = item.time;
}
private function keyhandler(event:KeyboardEvent):void{
if(event.keyCode == Keyboard.ENTER)
{
var v:Object = dg.editedItemPosition;
var index:int = dg.selectedIndex ;
if(v.columnIndex == 0)
{
//设置下个焦点位置之前,如果有渲染器或者编辑器的地方要手动设置表格的焦点
dg.setFocus();
//设置下个焦点位置dg.editedItemPosition = {columnIndex:1,rowIndex:v.rowIndex};
}
else if(v.columnIndex == 1)
{
dg.editedItemPosition = {columnIndex:2,rowIndex:v.rowIndex};
}
else if(v.columnIndex == 2)
{
dg.editedItemPosition = {columnIndex:0,rowIndex:v.rowIndex + 1};
}
}
}
]]>
</mx:Script>
<mx:Panel title="DataGrid Control Example" height="100%" width="100%"
paddingTop="10" paddingLeft="10" paddingRight="10">
<mx:Label width="100%" color="blue"
text="Select a row in the DataGrid control."/>
<mx:DataGrid id="dg" keyDown="keyhandler(event)" editable="true" width="100%" height="100%" rowCount="5" dataProvider="{dpFlat}" itemFocusOut="dg_itemFocusOutHandler(event)">
<mx:columns>
<mx:DataGridColumn dataField="name" headerText="Name" editable="true"/>
<mx:DataGridColumn dataField="time" headerText="Time" editorDataField="text">
<mx:itemEditor>
<mx:Component>
<mx:HBox width="100%" height="100%">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
public function get text():String
{
return dateField.text;
}
public override function set data(value:Object):void
{
var strToday:String = value.time;
var dateToday:Date = DateField.stringToDate(strToday, "YYYY-MM-DD");
dateField.selectedDate = dateToday;
}
]]>
</mx:Script>
<mx:DateField id="dateField" formatString="YYYY-MM-DD" width="100%" height="100%"/>
</mx:HBox>
</mx:Component>
</mx:itemEditor>
</mx:DataGridColumn>
<mx:DataGridColumn dataField="sprice" headerText="sprice" editable="true"/>
</mx:columns>
</mx:DataGrid>
<mx:Form width="100%" height="100%">
<mx:Label id="showLabel" text="{dg.selectedItem.time}"/>
</mx:Form>
</mx:Panel>
</mx:Application>