在flex 开发中我想要定义一个组件myComponent,并希望在继承它的组件subComponent里可以添加新的control。
myComponent:
myComponent:
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="400" height="300">
- <mx:Label x="111.5" y="70" text="Welcome to myComponent"/>
- </mx:Panel>
subComponent:
- <?xml version="1.0" encoding="utf-8"?>
- <MyComponent xmlns="*" xmlns:mx="http://www.adobe.com/2006/mxml" >
- <mx:Button />
- </MyComponent>
但是编译器会报错:Multiple sets of visual children have been specified for the MyComponent tag.
也即是flex 3不支持子类直接添加新的control 。 必须通过 重写childrenCreated方法来实现。新的代码如下:
MyComponent:
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="400" height="300" xmlns="*">
- <mx:Script>
- <![CDATA[
- import mx.core.UIComponent;
- import mx.controls.Button;
- public var control:UIComponent;
- override protected function childrenCreated():void
- {
- if (control != null)
- {
- myControlBar.addChild(control);
- }
- super.childrenCreated();
- }
- ]]>
- </mx:Script>
- <mx:Label x="111.5" y="70" text="Welcome to myComponent"/>
- <mx:ControlBar id="myControlBar" horizontalAlign="center">
- <!--new Object goes here -->
- </mx:ControlBar>
- </mx:Panel>
为了能演示效果,我们把子类改成一个application
SubApplication:
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns="*">
- <MyComponent>
- <!-- control is the property defined in MyComponent-->
- <control>
- <mx:Button label="OK"/>
- </control>
- </MyComponent>
- </mx:Application>