简单实现对flex dataGrid一列在某些行可编辑,在另一些行不可编辑

来源:互联网 发布:阿里云服务器有什么用 编辑:程序博客网 时间:2024/05/22 13:06
        Flex的dataGrid控件本身具备指定某列可编辑的功能,但在实际需求中往往要求对整列单元格并不全部可编辑。Flex dataGrid自身并未提供这样的接口,但是我们可以通过<mx:itemRenderer>和双向绑定来简单实现这一过程。下面代码展示了对小王的年龄可编辑,对小李的年龄不可编辑,同时通过ok键来反馈小李编辑后的年龄。

DataGridWithSomeEdit.mxml:

<?xml version="1.0" encoding="utf-8"?><mx:DataGrid xmlns:fx="http://ns.adobe.com/mxml/2009"  xmlns:s="library://ns.adobe.com/flex/spark"  xmlns:mx="library://ns.adobe.com/flex/mx" dataProvider="{dataSource}"><mx:columns><mx:DataGridColumn headerText="序号" dataField="id"/> <mx:DataGridColumn headerText="名称" dataField="name" /> <mx:DataGridColumn headerText="年龄" dataField="age"><mx:itemRenderer><fx:Component><mx:TextInput text="@{data.age}" enabled="{isEditable(data)}" borderStyle="{borderStyleShow(isEditable(data))}"  editable="{isEditable(data)}" restrict="0-9" ><fx:Script><![CDATA[import mx.collections.ArrayCollection;protected function borderStyleShow(isY:Boolean):String{if(true == isY){return "solid";}else{return "none";}}protected function isEditable(obj:Object):Boolean{if("小王" == obj.name){return true;}else{return false;}}]]></fx:Script></mx:TextInput></fx:Component></mx:itemRenderer></mx:DataGridColumn></mx:columns></mx:DataGrid>

 

Index.mxml:

<?xml version="1.0" encoding="utf-8"?><s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"    xmlns:s="library://ns.adobe.com/flex/spark"    xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:dataGridWithSomeRowCanEdit="dataGridWithSomeRowCanEdit.*"><s:layout><s:BasicLayout/></s:layout><fx:Script><![CDATA[import mx.collections.ArrayCollection;private var ds:ArrayCollection = new ArrayCollection([{id:1,name:"小王",age:12}, {id:2,name:"小李",age:30}, ]);import mx.controls.Alert;protected function button1_clickHandler(event:MouseEvent):void{var ac:ArrayCollection = dg.dataProvider as ArrayCollection; Alert.show(ac[0].age);}]]></fx:Script><mx:VBox><mx:Button label="ok" click="button1_clickHandler(event)" /><dataGridWithSomeRowCanEdit:DataGridWithSomeEdit id="dg"  dataProvider="{ds}"/></mx:VBox></s:Application>

 

其效果如下图所示:

 

        有一点值得提一下,在 <mx:TextInput text="@{data.age}"中使用了双向绑定,将TextInput的text值与dataGrid数据源的对象属性进行了双向绑定。这个绑定的意义,通过Index.mxml文件中button1_clickHandler方法的Alert过程可以看出,业务需求中要获取的是dataGrid更改后的数据源,但是没有这个双向绑定我们在TextInput更新的数据实质上并没有更新dataGrid数据源。我们知道dataGrid的数据源是无法进行双向绑定的,但是我们不能以此忽略了考量是否其数据源的具体对象可以进行双向绑定,但前提是要清楚双向绑定和dataGrid数据源实质是对象集合,每条dataGrid的记录就是一个对象。

不进行双向绑定的效果如下所示:

原创粉丝点击