Quick tip: DefaultProperty Metadata Tag

I hope to clarify function of DefaultProperty metadata tag with this article, while documentation may seems to be a little unclear. What it says is: The [DefaultProperty] metadata tag defines the name of the default property of the component when you use the component in an MXML file. It is correct and easy to imagine and understand once you see a little example. So here it is:

Application.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns:local="*" 
    layout="horizontal" >
<local:DefaultPropertyObject id="dpo">
    <![CDATA[
        hallo world
    ]]>
</local:DefaultPropertyObject>
<mx:Button click="trace(dpo.source)" label="trace"/>
</mx:Application>

DefaultPropertyObject.as

package
{
    [DefaultProperty("source")]
    
    public class DefaultPropertyObject extends Object
    {
        private var _source:String = "";
        
        public function DefaultPropertyObject()
        {
        }
        
        public function set source(value:String):void
        {
            _source = value;
        }
        
        public function get source():String
        {
            return _source;
        }
    }
}

What we did is, we defined source (any other property name can be used) as our default property and created setter for this property. What is this metadata tag good for?

  • for inserting long texts (upper example)
  • for creating components with custom children (lower example)

This way you can also define custom children for your component:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns:local="*" 
    layout="horizontal" >
<local:DefaultPropertyObject>
    <mx:Button label="button"/>
    <mx:Button label="button"/>
</local:DefaultPropertyObject>
</mx:Application>
package
{
    import flash.display.DisplayObject;
    
    import mx.containers.VBox;
    
    [DefaultProperty("contentChildren")]
    
    public class DefaultPropertyObject extends VBox
    {
        public function DefaultPropertyObject()
        {
        }
        
        // consider addChild in createChildren method
        public function set contentChildren(value:Object):void
        {
            for each(var item:DisplayObject in value)
                addChild(item);   // or myContentHolder.addChild(item)
        }
    }
}

Leave a comment

Please be polite and on topic. Your e-mail will never be published.