现在的位置: 首页 > 综合 > 正文

flex 3扩展自定义组件

2013年08月25日 ⁄ 综合 ⁄ 共 1675字 ⁄ 字号 评论关闭
在flex 开发中我想要定义一个组件myComponent,并希望在继承它的组件subComponent里可以添加新的control。
myComponent:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="400" height="300">
  3.     <mx:Label x="111.5" y="70" text="Welcome to myComponent"/>
  4.     
  5. </mx:Panel>

subComponent:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <MyComponent xmlns="*" xmlns:mx="http://www.adobe.com/2006/mxml" >
  3.     <mx:Button />
  4. </MyComponent>

但是编译器会报错:Multiple sets of visual children have been specified for the MyComponent tag.
也即是flex 3不支持子类直接添加新的control 。 必须通过 重写childrenCreated方法来实现。新的代码如下:
MyComponent:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="400" height="300" xmlns="*">
  3.     <mx:Script>
  4.         <![CDATA[
  5.             import mx.core.UIComponent;
  6.             import mx.controls.Button;
  7.    
  8.       
  9.         public var control:UIComponent;
  10.   
  11.         override protected function childrenCreated():void
  12.         {
  13.             if (control != null)
  14.             {
  15.                 myControlBar.addChild(control);
  16.             }     
  17.            
  18.             super.childrenCreated();
  19.         }
  20.         ]]>
  21.     </mx:Script>
  22.     <mx:Label x="111.5" y="70" text="Welcome to myComponent"/>
  23.     <mx:ControlBar id="myControlBar" horizontalAlign="center">
  24.     <!--new Object goes here -->   
  25.     </mx:ControlBar>
  26. </mx:Panel>

为了能演示效果,我们把子类改成一个application
SubApplication:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns="*">
  3.     <MyComponent>
  4.     <!-- control is the property defined in MyComponent-->
  5.       <control>
  6.         <mx:Button label="OK"/>
  7.       </control>
  8.     </MyComponent>
  9. </mx:Application>

【上篇】
【下篇】

抱歉!评论已关闭.