Creating a custom ComboBox item renderer in Flex

by Peter deHaan on September 25, 2007

The following example shows how you can create a simple ComboBox item renderer which displays multiline items in the ComboBox control’s drop down menu.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/25/creating-a-custom-combobox-item-renderer-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="top"
        backgroundColor="white">

    <mx:XMLList id="statesXMLList">
        <state abbrev="AL" name="Alabama" />
        <state abbrev="AK" name="Alaska" />
        <state abbrev="AZ" name="Arizona" />
        <state abbrev="AR" name="Arkansas" />
        <state abbrev="CA" name="California" />
        <state abbrev="CO" name="Colorado" />
        <state abbrev="CT" name="Connecticut" />
    </mx:XMLList>

    <mx:ComboBox id="comboBox"
            prompt="Please select a State..."
            dataProvider="{statesXMLList}"
            rowCount="3"
            labelField="@name"
            itemRenderer="ComboBoxItemRenderer" />

</mx:Application>

View ComboBoxItemRenderer.mxml

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/25/creating-a-custom-combobox-item-renderer-in-flex/ -->
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
        styleName="plain">

    <mx:Label text="{data.@name}"
            fontSize="11"
            fontWeight="bold" />
    <mx:Label text="{data.@abbrev}"
            fontSize="9"
            paddingLeft="10" />

</mx:VBox>

View source is enabled in the following example.

{ 15 comments… read them below or add one }

mary August 13, 2009 at 2:51 pm

excellent. Is there a way to output text when a state is selected? I would like give a brief description about the types of flowers for that particular state

thanks

Reply

Peter deHaan August 13, 2009 at 4:37 pm

@mary,

Yeah, there are a few ways, but this should work as a starting point:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="top"
        backgroundColor="white">
 
    <mx:Script>
        <![CDATA[
            private function comboBox_labelFunc(item:XML):String {
                return item.@name + " (" + item.@abbrev + ")";
            }
        ]]>
    </mx:Script>
 
    <mx:XMLList id="statesXMLList">
        <state abbrev="AL" name="Alabama" desc="Yeah, we got some flowers. Some pretty nice ones." />
        <state abbrev="AK" name="Alaska" desc="Not many flowers here. Mostly too cold. But we have snow." />
        <state abbrev="AZ" name="Arizona" desc="Mostly prickly flowers here. And scorpions." />
        <state abbrev="AR" name="Arkansas" desc="I assume we have some flowers." />
        <state abbrev="CA" name="California" desc="Lots of flowers." />
        <state abbrev="CO" name="Colorado" desc="Yep, flowers here too." />
        <state abbrev="CT" name="Connecticut" desc="Probably. I don't know geography or flowers." />
    </mx:XMLList>
 
    <mx:ComboBox id="comboBox"
            prompt="Please select a State..."
            dataProvider="{statesXMLList}"
            labelFunction="comboBox_labelFunc" />
 
    <mx:Text id="txt"
            text="{comboBox.selectedItem.@desc}"
            width="{comboBox.width}" />
 
</mx:Application>

Peter

Reply

mary August 15, 2009 at 1:21 pm

Thank you very much. Your description on flowers was hilarious – it made my day.

I am having some troubles with the text, I have added wordwrap=true but still it doesnt come out correct. Is there a way to insert a break so that I can make sure it goes to the next line?

Reply

Peter deHaan August 15, 2009 at 5:48 pm

@mary,

If you want an explicit line break, add a “\n” in the text. Or make sure that your <mx:Text/> control sets the width property so it will wrap when the text reaches a certain width.

Peter

Reply

Sharat October 8, 2009 at 12:13 pm

Hi,

First of all, thanks for the code. I have ended up using this in my application. One thing I want to know is how do you select a value by default? Say, I have to select California by default. I haven’t found a way to do it yet. Please let me know.

Thanks,
Sharat

Reply

Peter deHaan October 8, 2009 at 12:30 pm

@Sharat,

The easiest way would be to set the selectedIndex property to 4.

Peter

Reply

Sharat October 8, 2009 at 12:34 pm

Peter,

Thanks for the quick response. Yes, that would be the easiest but is there a way to do it based on value? In my application, I get the text, say “California” and the index might not be consistent all the time.

Thanks,
Sharat

Sharat October 8, 2009 at 12:37 pm

I tried doing selectedItem = “text” and it doesn’t seem to work.

Peter deHaan October 8, 2009 at 12:40 pm

@Sharat,

Check out this article by Adobe’s Alex Harui; “SelectedItem and ComboBox”.

Peter

Sharat October 8, 2009 at 12:47 pm

Peter,

Thanks a lot. This is exactly what I was looking for.

Sharat

Peter deHaan October 8, 2009 at 12:52 pm

Or, if you just wanted the easy solution, try the following example which uses E4X to quickly parse the states XML by state name to find the match (so you can set the selectedItem property):

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/25/creating-a-custom-combobox-item-renderer-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="top"
        backgroundColor="white">
 
    <mx:Script>
        <![CDATA[
            protected function selectStateByName(stateName:String):void {
                var states:XMLList = statesXMLList.(@name == stateName);
                if (states.length() > 0) {
                    comboBox.selectedItem = states[0];
                } else {
                    comboBox.selectedIndex = -1;
                }
            }
        ]]>
    </mx:Script>
 
    <mx:XMLList id="statesXMLList">
        <state abbrev="AL" name="Alabama" />
        <state abbrev="AK" name="Alaska" />
        <state abbrev="AZ" name="Arizona" />
        <state abbrev="AR" name="Arkansas" />
        <state abbrev="CA" name="California" />
        <state abbrev="CO" name="Colorado" />
        <state abbrev="CT" name="Connecticut" />
    </mx:XMLList>
 
    <mx:ApplicationControlBar dock="true">
        <mx:Button label="Select California"
                themeColor="haloGreen"
                click="selectStateByName('California');" />
        <mx:Button label="Select Oregon"
                themeColor="red"
                click="selectStateByName('Oregon');" />
    </mx:ApplicationControlBar>
 
    <mx:ComboBox id="comboBox"
            prompt="Please select a State..."
            dataProvider="{statesXMLList}"
            rowCount="3"
            labelField="@name"
            itemRenderer="ComboBoxItemRenderer" />
 
</mx:Application>

You’ll notice that the California button selects the correct state, whereas the Oregon button resets the selectedIndex property to -1, since no matches were found in the XML. Also note that I haven’t tested the code very thoroughly. I don’t know how it would handle multiple states named “California” in the data provider, and I also never tested this in a initialize or creationComplete handler to see if it correctly selects a state by default.

Peter

Sharat October 8, 2009 at 3:08 pm

Peter,

Thanks again! Works like a charm. I dont care about the other handlers and the code does everything I need.

Thanks,
Sharat

ATD December 8, 2009 at 1:56 am

Hi,

I tried to adapt this example to Flex 4, but haven’t been able to get it working.

Reply

juanabreu January 7, 2010 at 9:24 pm

thank you for the awesome post i have a really easy question for someone of your caliber. i ahve more then a couple of columns on my datagrid and i would like to test for the length of the strings and when the string is greated then night i would like to make then red. when i try one column i have no problem as soon as i expand to more then one column i run into trouble can you please help me.

 if (parseFloat(data.col1.length) != 9){
        (setStyle("color", (parseFloat(data.col1.length) != 9) ? NEGATIVE_COLOR : POSITIVE_COLOR))
    }
	if (parseFloat(data.col2.length) > 15){
	(setStyle("color", (parseFloat(data.col2.length) > 15) ? NEGATIVE_COLOR : POSITIVE_COLOR))
    }
		//:setStyle("color", (parseFloat(data.col2.length) > 15) ? NEGATIVE_COLOR : POSITIVE_COLOR);
    }
    }

Reply

bwp March 17, 2010 at 8:24 am

Is there a way to maintain the two lines of text once an item has been selected. I need to display two lines of text in the closed state. Is this possible in Flex 3?

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: