flex 简单的增删改查 另外添加checkbox grid

组件:components.MgmtGrid.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml"
		  width="100%"
		  height="100%"
		  creationComplete="init()">
	<mx:VBox width="100%"
			 height="100%">
		<mx:DataGrid width="100%"
					 height="100%"
					 styleName="{_gridStyleName}"
					 id="_grid"
					 dataProvider="{_dataAc}"
					 headerRelease="headerRelease(event)"/>
		<mx:HRule width="100%"
				  strokeWidth="1"
				  strokeColor="#CCCCCC"/>
		<mx:HBox borderStyle="none"
				 height="30"
				 width="100%"
				 horizontalGap="0"
				 paddingLeft="10"
				 paddingRight="10"
				 verticalAlign="middle">
			<mx:HBox borderStyle="none"
					 width="100%"
					 horizontalAlign="left"
					 id="_boxFuncBtn"/>
			<mx:Spacer width="100%"/>
			<mx:Text text="{'  第'+_pageIndex+'页/共'+_pageCount+'页'+'  共'+_totalRecord+'条记录'}"
					 fontWeight="{_pagerFontWeight}"
					 fontSize="{_pagerFontSize}"/>
			<mx:LinkButton id="_lbtnFirst"
						   label="首页"
						   click="_pageIndex=0;load();"
						   enabled="{_lbtnPrevious.enabled}"
						   fontWeight="{_pagerFontWeight}"
						   fontSize="{_pagerFontSize}"/>
			<mx:LinkButton id="_lbtnPrevious"
						   label="上一页"
						   click="_pageIndex--;load();"
						   enabled="{_pageIndex!=1?true:false}"
						   fontWeight="{_pagerFontWeight}"
						   fontSize="{_pagerFontSize}"/>
			<mx:LinkButton id="_lbtnNext"
						   label="下一页"
						   click="_pageIndex++;load();"
						   enabled="{_pageCount>(_pageIndex)?true:false}"
						   fontWeight="{_pagerFontWeight}"
						   fontSize="{_pagerFontSize}"/>
			<mx:LinkButton id="_lbtnLast"
						   label="尾页"
						   click="_pageIndex=_pageCount;load();"
						   enabled="{_lbtnNext.enabled}"
						   fontWeight="{_pagerFontWeight}"
						   fontSize="{_pagerFontSize}"/>
			<mx:NumericStepper id="_nsPageNum"
							   stepSize="1"
							   minimum="1"
							   maximum="{_pageCount}"
							   enabled="{_lbtnJump.enabled}"
							   value="{_pageIndex}"
							   fontWeight="{_pagerFontWeight}"
							   fontSize="{_pagerFontSize}"/>
			<mx:LinkButton id="_lbtnJump"
						   label="跳转"
						   click="_pageIndex=_nsPageNum.value;load();"
						   enabled="{_pageCount>1?true:false}"
						   fontWeight="{_pagerFontWeight}"
						   fontSize="{_pagerFontSize}"/>
		</mx:HBox>
	</mx:VBox>
	<mx:DataGridColumn sortable="false"
					   id="_columnCheckBox"
					   draggable="false"
					   width="50"
					   textAlign="center">
		<mx:headerRenderer>
			<mx:Component>
				<mx:CheckBox label="全选"
							 selected="{outerDocument._selectAll}"
							 click="outerDocument.clickAll(data)"/>
			</mx:Component>
		</mx:headerRenderer>
		<mx:itemRenderer>
			<mx:Component>
				<mx:CheckBox selected="{outerDocument.isSelected(data)}"
							 click="outerDocument.clickSingle(data)"/>
				<!-- <mx:CheckBox selected="{outerDocument.isSelected(data)}" click="data[outerDocument._selectedField] = !data[outerDocument._selectedField]"/> -->
			</mx:Component>
		</mx:itemRenderer>
	</mx:DataGridColumn>

	<!-- hide properties -->
	<mx:Metadata>
		[Exclude(name="_grid", kind="property")]
		[Exclude(name="_columnCheckBox", kind="property")]
		[Exclude(name="_boxFuncBtn", kind="property")]
		[Exclude(name="_lbtnFirst", kind="property")]
		[Exclude(name="_lbtnPrevious", kind="property")]
		[Exclude(name="_lbtnNext", kind="property")]
		[Exclude(name="_lbtnLast", kind="property")]
		[Exclude(name="_nsPageNum", kind="property")]
		[Exclude(name="_lbtnJump", kind="property")]
	</mx:Metadata>

	<mx:Script>
		<![CDATA[
			import mx.charts.BubbleChart;
			import mx.controls.Button;
			import mx.events.DataGridEvent;
			import mx.collections.ArrayCollection;

			[Bindable]
			private var _pageSize:int=20;
			[Bindable]
			private var _pageIndex:int=1;
			[Bindable]
			private var _pageCount:int=1;
			[Bindable]
			private var _totalRecord:int=0;
			[Bindable]
			private var _pagerFontWeight:String="normal";
			[Bindable]
			private var _pagerFontSize:int=12;
			[Bindable]
			private var _gridStyleName:String="";
			[Bindable]
			private var _enableCheckBox:Boolean=true;
			[Bindable]
			private var _gridColumns:Array=new Array();
			[Bindable]
			internal var _selectAll:Boolean=false;
			[Bindable]
			internal var _selectedField:String="selected";
			[Bindable]
			private var _dataAc:ArrayCollection=new ArrayCollection;

			private var _funcLoad:Function=null;
			private var _localSort:Boolean=true;
			private var _sortObject:Object=null;
			private var _btnDescs:Array=null;
			private var _btnStyleName:String="";
			private var _btnHandler:Function=null;

			/**
			 * 设置分页信息。<br>
			 * 在外部获取分页的信息,包括页数、当前页、所有记录数,然后告诉MgmtGrid进行显示。<br>
			 * @param pc 分页数(pageCount)
			 * @param pi 当前页码(pageIndex),从1开始
			 * @param tr 所有记录数量(totalRecord)
			 * */
			public function setPageInfo(pc:int, pi:int, tr:int):void
			{
				this._pageCount=pc;
				this._pageIndex=pi;
				this._totalRecord=tr;
			}

			/**
			 * 设置分页大小,默认是20。<br>
			 * */
			public function set pageSize(ps:int):void
			{
				this._pageSize=ps;
			}


			/**
			 * 设置数据加载回调方法。系统会根据通过该方法通知外部获取数据,并给定数据相关参数。<br>
			 * 方法定义如下:<br>
			 * <code>function fun(ps:int, pi:int, so:Object)</code><br>
			 * 其中ps是分页大小,pi是当前页码,so是排序参数。<br>
			 * 排序参数是一个Object对象,拥有2个参数:<br>
			 * <ul>
			 * <li>index</li>排序列序号,指明用那列进行排序
			 * <li>desc</li>是否是升序,true表示升序,false表示降序
			 * 外部获取数据接口要根据这些参数向服务器请求数据<br>
			 * */
			public function set loadFunc(f:Function):void
			{
				this._funcLoad=f;
			}

			/**
			 * 是否本地排序。true的话,则不需要向服务器请求全局排序,只是利用flex自身的排序功能<br>
			 * 在当前显示页面排序。<br>
			 * */
			public function set localSort(lc:Boolean):void
			{
				this._localSort=lc;
			}


			/**
			 * 设置分页字体宽度,默认是normal。
			 * */
			public function set pagerFontWeight(w:String):void
			{
				this._pagerFontWeight=w;
			}

			/**
			 * 设置分页字体大小,默认是12。
			 * */
			public function set pagerFontSize(s:int):void
			{
				this._pagerFontSize=s;
			}

			/**
			 * 设置表格的式样名称。该式样将会影响表格的显示外观。
			 * */
			public function set gridStyleName(s:String):void
			{
				this._gridStyleName=s;
			}

			/**
			 * 是否需要显示复选框。显示复选框时,有全选功能,这个比较常用<br>
			 * 如果选择复选框,那么选中的数据项目根据复选框的状态来判断。<br>
			 * 如果没有复选框,那么选中的数据项目根据DataGrid选中的项目来判断。<br>
			 * */
			public function set enableCheckBox(b:Boolean):void
			{
				this._enableCheckBox=b;
			}

			/**
			 * 设置表格列DataGridColumn
			 * */
			public function set gridColumns(columns:Array):void
			{
				this._gridColumns=columns;
			}

			/**
			 * 设置选中列的标识。<br>
			 * 该项只有在enableCheckBox=true的时候有效。<br>
			 * 系统会根据这个字段来判断是否选中的状态。这个字段没有实际意义,<br>
			 * 不要与数据列冲突。<br>
			 * */
			public function set selectedField(s:String):void
			{
				this._selectedField=s;
			}

			/**
			 * 按钮描述。<br>
			 * 系统会根据按钮描述生成相关功能按钮,这些按钮被点击后,会触发<br>
			 * 按钮处理方法,用户可以根据处理方法里的按钮id执行相关操作。<br>
			 * 按钮描述对象有id、label、styleName几个字段。<br>
			 * */
			public function set btnDescs(arr:Array):void
			{
				this._btnDescs=arr;
			}

			/**
			 * 全局按钮样式名称。<br>
			 * 如果按钮描述对象里设置了样式名称,则根据按钮自己的样式绘制,<br>
			 * 否则根据全局按钮样式绘制。<br>
			 * */
			public function set btnStyleName(s:String):void
			{
				this._btnStyleName=s;
			}

			/**
			 * 设置按钮点击处理方法。<br>
			 * 该方法定义如下:<br>
			 * <code>function handler(id:String):void</code><br>
			 * id是被点击的按钮对应的id<br>
			 * */
			public function set btnHandler(f:Function):void
			{
				this._btnHandler=f;
			}

			/**
			 * 获得选中的数据项,如果选中多项,则返回第一项。<br>
			 * @return 返回第一个选中的项目,如果没有选中,则返回null
			 * */
			public function get selectedItem():Object
			{
				if (this._enableCheckBox)
				{
					for each (var o:Object in this._dataAc)
					{
						if (isSelected(o))
						{
							return o;
						}
					}
					return null;
				}
				return this._grid.selectedItem;
			}

			/**
			 * 获得选中的数据项。<br>
			 * @return 返回装有选中项的Array对象,如果没有选中项,则返回null
			 * */
			public function get selectedItems():Object
			{
				if (this._enableCheckBox)
				{
					var arr:Array=new Array;
					for each (var o:Object in this._dataAc)
					{
						if (isSelected(o))
						{
							arr.push(o);
						}
					}
					return arr.length == 0 ? null : arr;
				}
				return this._grid.selectedItems;
			}

			/**
			 * 增加一个数据项
			 * */
			public function addData(o:Object):void
			{
				this._dataAc.addItem(o);
			}

			/**
			 * 增加多个数据项
			 * @param o 多个数据项,必须是collection
			 * */
			public function addDatas(o:Object):void
			{
				for each (var d:Object in o)
				{
					addData(d);
				}
			}

			/**
			 * 删除数据项
			 * @param o 要删除的数据项
			 * */
			public function removeData(o:Object):void
			{
				var i:int=this._dataAc.getItemIndex(o);
				if (i >= 0)
				{
					this._dataAc.removeItemAt(i);
				}
			}

			/**
			 * 删除多个数据项
			 * @param o 要删除的数据项,必须为collection
			 * */
			public function removeDatas(o:Object):void
			{
				for each (var i:Object in o)
				{
					removeData(i);
				}
			}

			/**
			 * 更新数据字段
			 * @param o 要更新的数据
			 * @param field 数据的字段名
			 * @param v 新的字段值
			 * */
			public function updateData(o:Object, field:String, v:Object):void
			{
				var i:int=this._dataAc.getItemIndex(o);
				if (i >= 0)
				{
					o[field]=v;
					this._dataAc.itemUpdated(o, field, null, v);
				}
			}
			public function updateDataObj(oldItem:Object,newItem:Object):void
			{
				var i:int=this._dataAc.getItemIndex(oldItem);
				if (i >= 0)
				{
					for(var field in newItem)
					{
						oldItem[field]=newItem[field];
						this._dataAc.itemUpdated(oldItem, field, null, newItem[field]);
					}
				}
				
			}
			public function refresh():void
			{
				this._dataAc.refresh();
			}

			/**
			 * 如果组件不需要再使用,强烈建议调用destroy进行资源释放,<br>
			 * 以防内存泄漏。<br>
			 * */
			public function destroy():void
			{
				unInitButtons();
			}

			private function init():void
			{
				initColumns();
				initButtons();
				load();
			}

			private function initColumns():void
			{
				var arr:Array=new Array;
				if (this._enableCheckBox)
				{
					arr.push(this._columnCheckBox);
				}
				for each (var o:Object in this._gridColumns)
				{
					arr.push(o);
				}
				this._grid.columns=arr;
			}

			private function initButtons():void
			{
				if (this._btnDescs != null)
				{
					for each (var o:Object in this._btnDescs)
					{
						var btn:Button=new Button;
						btn.id=o.id;
						btn.label=o.label;
						btn.styleName=(o.styleName == undefined) ? this._btnStyleName : o.styleName;
						btn.addEventListener(MouseEvent.CLICK, onBtnClick);
						this._boxFuncBtn.addChild(btn);
					}
				}
			}

			private function unInitButtons():void
			{
				for each (var o:Object in this._boxFuncBtn.getChildren())
				{
					Button(o).removeEventListener(MouseEvent.CLICK, onBtnClick);
				}
			}

			private function onBtnClick(e:MouseEvent):void
			{
				if (e.currentTarget is Button)
				{
					if (this._btnHandler != null)
					{
						this._btnHandler(Button(e.currentTarget).id);
					}
				}
			}

			private function load():void
			{
				this._dataAc.removeAll();
				if (this._funcLoad != null)
				{
					this._funcLoad(this._pageSize, this._pageIndex, this._sortObject);
				}
			}

			internal function clickAll(data:Object=null):void
			{
				this._selectAll=!this._selectAll;
				for each (var o:Object in this._dataAc)
				{
					o[this._selectedField]=this._selectAll;
				}

				this._grid.invalidateList();
			}

			internal function clickSingle(data:Object=null):void
			{
				data[this._selectedField]=!isSelected(data);
				this._grid.invalidateList();
			}

			internal function isSelected(data:Object):Boolean
			{
				var v:Object=String(data[this._selectedField]);
				return v == "true";
			}


			private function headerRelease(event:DataGridEvent):void
			{
				if (!this._localSort)
				{
					var dc:DataGridColumn=DataGridColumn(event.itemRenderer.data);
					if (this._sortObject == null)
					{
						this._sortObject=new Object;
					}
					this._sortObject.index=this._enableCheckBox ? (event.columnIndex - 1) : event.columnIndex;
					this._sortObject.desc=dc.sortDescending;
					load();
				}
			}
		]]>
	</mx:Script>
</mx:Panel>


sample.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
				layout="vertical"
				xmlns:components="components.*"
				creationComplete="init()">
	<components:MgmtGrid id="grid"
						 width="80%"
						 height="400"
						 title="Hello"
						 styleName="ztGridPanel"
						 pagerFontSize="12"
						 gridColumns="{cols}"
						 enableCheckBox="true"
						 selectedField="selected"
						 localSort="false"
						 loadFunc="load"
						 pageSize="2"
						 btnDescs="{btnDescs}"
						 btnHandler="btnHandler"
						 btnStyleName="ztGridBtn"
						 gridStyleName="ztDataGrid">
	</components:MgmtGrid>
	<!---->
	<mx:Array id="cols">
		<mx:DataGridColumn headerText="Text"
						   dataField="label"
						   sortable="false"/>
		<mx:DataGridColumn headerText="Integer"
						   dataField="iv"/>
		<mx:DataGridColumn headerText="Long"
						   dataField="lv"/>
		<mx:DataGridColumn headerText="Boolean"
						   dataField="selected"/>
	</mx:Array>
	
	
	<mx:Style>
		.ztGridPanel {
		   borderColor: #0099ff;
		   borderAlpha: 1;
		   borderThicknessLeft: 1;
		   borderThicknessTop: 1;
		   borderThicknessBottom: 1;
		   borderThicknessRight: 1;
		   cornerRadius: 0;
		   headerHeight: 25;
		   backgroundAlpha: 1;
		   headerColors: #3399ff, #0066ff;
		   titleStyleName: "ztGridpanelTitle";
		   dropShadowEnabled: false;
		}

		.ztGridpanelTitle {
		   textAlign: center;
   		   fontFamily: Arial;
   		   fontSize: 13;
   		   font-weight:bold;
   		   color:#ffffff;
		}
		
		.ztDataGrid {
		   headerStyleName: "ztdataGridHeaderStyle";
		}

		.ztdataGridHeaderStyle {
		   color: #666666;
		   fontFamily: Arial;
		   fontSize: 12;
		   textAlign: center;
		   font-weight:bold;
		}
		.ztGridBtn {
			fontSize: 10;
			textAlign: center;
			font-weight:normal;
		}
	</mx:Style>
	<mx:Button click="func()"
			   label="Show Select"/>
	<mx:Button click="addFunc('add')"
			   label="Add"/>
	<mx:Script>
		<![CDATA[
			import components.MgmtGrid;
			import mx.controls.Alert;
			import mx.collections.ArrayCollection;
			import mx.managers.PopUpManager;
			[Bindable]
			private var btnDescs:Array=new Array({"id": "btnAdd", "label": "添加"}, {"id": "btnModify", "label": "修改"}, {"id": "btnDelete", "label": "删除"});
			
			[Bindable]   
            public var dgProvider:ArrayCollection; 

//			private var grid:MgmtGrid = new MgmtGrid;

			private function func():void
			{
				var arr:Object=grid.selectedItems;
				if (arr != null)
				{
					var index:int=0;
					for each (var o:Object in arr)
					{
						index++;
						trace(o.@label + " " + o.@iv + " " + o.@lv + " " + o.@selected);

					}
					Alert.show("您选择了" + index + "个元素", "title");
				}
			}


			//初始化表格数据
			/** ArrayCollection=new ArrayCollection;*/
			 private function initFunction():ArrayCollection
			 {
			 	var ret:ArrayCollection=new ArrayCollection;
			 	var prodIndex:int = 1;
			 	for (var z:int=0; z < 10; z++)   
                {   
                    var prod1:Object={};   
                    prod1.label=prodIndex * 7;   
                    prod1.iv=prodIndex; 
                    prod1.lv=prodIndex++; 
                    prod1.selected  =  prodIndex%2==0?"true":"false";
                  ret.addItem(prod1);
                   
                }
			 	return ret;
			 
			 }  
			
			private function init():void
			{
				
				//this._grid.dataProvider = xml.item;//
				//this._grid.dataProvider = new Array({"label":"Hello", "iv":"32", "lv":"32.00"}, {"label":"World", "iv":"31", "lv":"31.00"});
				//grid.addDatas(xml.item);
				//	this.grid.gridColumns = cols;
				//	this.grid.enableCheckBox = true;
				//	this.grid.styleName = "ztGridPanel";
				//	this.grid.btnDescs = btnDescs;
				//	this.grid.loadFunc = load;
				//	this.grid.selectedField = "@selected";
				//	this.addChild(this.grid);
			}

			private function addFunc(tFlag:String):void
			{
				
				var auWindow:AUSample =    
					AUSample(PopUpManager.createPopUp(this, AUSample, true));
					auWindow.title = tFlag=="add"?"添加窗口":"修改窗口";
					auWindow.flag = tFlag=="add"?"add":"mod";
					auWindow.parentAddRow = addRow;
					auWindow.parentModRow = modRow;
				 	PopUpManager.centerPopUp(auWindow);   
				
			}
			private function addRow(row:Object):void
			{
				this.grid.addData(row);
			}
			private function modRow(row:Object):void
			{
				var selectedItem :Object = this.grid.selectedItem ;
				if(selectedItem != null)
				{
					this.grid.updateDataObj(selectedItem,row);
				}
			}
			
			
			
			private function load(ps:int, pi:int, so:Object):void
			{
				trace(ps + " " + pi);
				if (so != null)
				{
					trace(so.index + "  " + so.desc);
				}
				var ret:ArrayCollection = initFunction();
				//this.grid.setPageInfo(allPage, nowPage, pagesize);
				this.grid.setPageInfo(2, 1, 4);
				this.grid.addDatas(ret);
			}

			private function btnHandler(id:String):void
			{
				if (id == "btnDelete")
				{
					var o:Object=this.grid.selectedItems;
					if (o != null)
					{
						this.grid.removeDatas(o);
					}
				}
				else if (id == "btnModify")
				{
					o=this.grid.selectedItem;
					if (o != null)
					{
						//this.grid.updateData(o, "@label", "new");
						addFunc("mod");
					}
				}
				else if (id == "btnAdd")
				{
					addFunc("add");
					
				}
			}
		]]>
	</mx:Script>
</mx:Application>



弹出窗口AUSample.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml"
				layout="absolute"
				width="348"
				height="308"
				fontSize="12"
				creationComplete="init()"
				>
	<mx:Script>
	   <![CDATA[
	   	import mx.managers.PopUpManager;
	   	import mx.controls.Alert;
	   	//初始化标志
	   	public var flag:String="";
	   	public var parentAddRow:Function;
	   	public var parentModRow:Function;
	   	
	   	public function init():void
	   	{
	   		if(flag == "mod")
	   		{
	   		label2.text = "mod";
	   		}
	   		else if(flag == "add")
	   		{
	   			label2.text = "add";
	   		
	   		}
	   	}
	   	
	   	 //确定键后  
	        public function setData():void
	        {
	        	var formObject:Object = new Object();
	        	formObject.label = label2.text;
	        	formObject.iv = iv.text;
	        	formObject.lv = lv.text;
	        	formObject.selected = selected.text;
	        	if(flag == "mod")
		   		{
		   			parentModRow(formObject);
		   		}
		   		else if(flag == "add")
		   		{
		   			
		   			parentAddRow(formObject);
		   		}
	        	
	        	 PopUpManager.removePopUp(this);
	        
	        }
	       //关闭窗口,同时刷新父窗口
	         private function Close():void{
	             PopUpManager.removePopUp(this);
	         }
	   
	    ]]>
     </mx:Script> 
	<mx:Form x="0"
			 y="0"
			 width="100%"
			 height="220">

		<mx:FormItem label="Text"
					 width="235">
			<mx:TextInput id="label2"/>
		</mx:FormItem>
		<mx:FormItem label="Integer"
					 width="235">
			<mx:TextInput id="iv"/>
		</mx:FormItem>
		<mx:FormItem label="Long"
					 width="235">
			<mx:TextInput id="lv"/>
		</mx:FormItem>
		<mx:FormItem label="Boolean"
					 width="235">
			<mx:TextInput id="selected"/>
		</mx:FormItem>
	</mx:Form>
	<mx:ControlBar height="40"
				   y="114"
				   horizontalAlign="right"
				   cornerRadius="0"
				   alpha="1.0">
		<mx:Button label="确定"
				   click="setData()"/>
		<mx:Button label="关闭"
				   click="Close()"/>
	</mx:ControlBar>
</mx:TitleWindow>


你可能感兴趣的:(xml,F#,Flex)