Monday, April 11, 2011

Can I use a bindable string for a ComboBox prompt?

The following displays a ComboBox with the text "Select One":

*This is pseudo code

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:ComboBox prompt="Select One">
        <mx:dataProvider>
            <mx:Array>
                <mx:Object label="Obj 1" />
                <mx:Object label="Obj 2" />
                <mx:Object label="Obj 3" />
            </mx:Array>
        </mx:dataProvider>
    </mx:ComboBox>
</mx:Application>

However, the following displays a ComboBox with the text "Obj 1" (the label of the first item):

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            [Bindable]
            private var promptText:String = "Select One";
        ]]>
    </mx:Script>

    <mx:ComboBox prompt="{promptText}">
        <mx:dataProvider>
            <mx:Array>
                <mx:Object label="Obj 1" />
                <mx:Object label="Obj 2" />
                <mx:Object label="Obj 3" />
            </mx:Array>
        </mx:dataProvider>
    </mx:ComboBox>
</mx:Application>

Why can't I use a Bindable String for the prompt???

From stackoverflow
  • This worked:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
        <mx:Script>
            <![CDATA[
                [Bindable]
                private var promptText:String = "Select One";
            ]]>
        </mx:Script>
    
        <mx:ComboBox selectedIndex="-1" prompt="{promptText}">
            <mx:dataProvider>
                <mx:Array>
                    <mx:Object label="Obj 1" />
                    <mx:Object label="Obj 2" />
                    <mx:Object label="Obj 3" />
                </mx:Array>
            </mx:dataProvider>
        </mx:ComboBox>
    </mx:Application>
    

    I can't figure out why I have to explicitly set selectedIndex to -1, but, it works!

    joshtynjala : Binding happens a bit later than component creation. I'm guessing that the ComboBox defaults to selecting the first item if you don't specify a prompt. So, the ComboBox gets created, it validates and choose the first item, and then the binding kicks in.
    Eric Belair : Yeah, that makes sense.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.