Flex学习记录(动态填充菜单)

<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
creationComplete="initApp(event)">
<mx:MenuBar id="menu" dataProvider="{menu_dp}"/>
<mx:Script>
	<![CDATA[
		import mx.collections.ArrayCollection;
		import mx.events.FlexEvent;
		[Bindable]
		private var menu_dp:ArrayCollection;
		private function initApp(evt:FlexEvent):void {
		var temp:Array = new Array();
		var subNodes:ArrayCollection = new ArrayCollection([
			{label:"New"},
			{label:"Open"},
			{label:"Close",enabled:false}]);
		temp.push({label:"File",children:subNodes});
		temp.push({label:"Edit"});
		temp.push({label:"Source"});

		subNodes = new ArrayCollection( [
			{label:"50%", type:"radio", groupName:"one"},
			{label:"100%", type:"radio", groupName:"one",
			selected:true},
			{label:"150%", type:"radio", groupName:"one"}]);
		temp.push({label:"View",children:subNodes});
		menu_dp = new ArrayCollection(temp);
		/*使用Collection 对象(例如ArrayCollection
		或者XMLListCollection)可以确保数据的任意变化
		都会触发控件相因的更新显示。*/
		}
		private function editMenu():void {
		var itemToEdit:Object;
		try {
			// 获取MENU对象付给itemToEdit。
			itemToEdit = menu_dp.getItemAt(int(menuIdx.text));
			// 如果SUBMENU入力的话
			if(subMenuIdx.text) {
				// 获取MENU下拉列表的第subMenuIdx个子对象付给itemToEdit。
				itemToEdit = 
				itemToEdit.children.getItemAt(int(subMenuIdx.text));
			}
			itemToEdit.label = label_ti.text;
			/* itemUpdated 方法来请求显示内容更新是非常重要的。
			不然的话,数据会修改但是显示可能还是显示旧的数据。*/
			menu_dp.itemUpdated(itemToEdit);
		}
		catch(ex:Error){
		trace("could not retrieve menu item");
		}
		}
	]]>
</mx:Script>
<!-- 这是一个基础的表单,使用了输入控件允许你来指定数组的索引
来获取指定的菜单项。在menuIdx 输入框输入0 然后在subMenuIdx
 输入框留空就会得到顶层File 菜单。-->
<mx:Form>
	<mx:FormHeading label="Menu Editor"/>
	<mx:FormItem label="Menu Index">
		<mx:TextInput id="menuIdx" restrict="0-9" text="0" width="20"/>
	</mx:FormItem>
	<mx:FormItem label="Sub-Menu Index">
		<mx:TextInput id="subMenuIdx" restrict="0-9" width="20"/>
	</mx:FormItem>
	<mx:FormItem label="Menu Label">
		<mx:TextInput id="label_ti"/>
	</mx:FormItem>
	<mx:FormItem>
		<!--editMenu 方法会被调用,指定的索引来
		获取菜单项的索引并且修改它的显示文字-->
		<mx:Button label="Edit" click="editMenu()"/>
	</mx:FormItem>
</mx:Form>

</mx:Application>

你可能感兴趣的:(Flex)