Monday, July 30, 2012

Flex - Combobox as Dropdownlist

Creating CustomComboBoxDropDownList – Use to switch from ComboBox to DropDownList and v/s.
I was wondering how developer can use same component to switch from ComboBox to DropDownList and v/s. so I did some workaround to find out the solution, Here we go –
Q. - How to user combobox as dropdownlist by using user defined custom property.
Steps to create custom component. Consider file name as below: -
Class Name: - CustomComboBoxDropDownList.MXML

Step 1: - Create custom component which extend combobox
Ex: -
s:ComboBox xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" width="100%" height="100%"
change="onComBoxIndexChange(event)" creationComplete="setPromptText()"
skinClass="skins.SkinComboBox ">

     
     
       fx:Script>

      import mx.controls.Alert;
                 
      import skins.SkinDropDownList;
                 
      import spark.components.DropDownList;
      import spark.core.IDisplayText;
      import spark.events.IndexChangeEvent;
                 
      private var promptText:String;
                 
      public var _useAsDropDown:Boolean = false;
                 
      private function setPromptText():void
      {
        promptText = this.prompt;
        setUserSelectedSkin();
      }
                 
      public function set useAsDropDown(value:Boolean):void
      {
         _useAsDropDown = value;
      }
                 
      public function get useAsDropDown():Boolean
      {
          return _useAsDropDown;
      }
                 
      private function setUserSelectedSkin():void
      {
         if(_useAsDropDown)
         {
          this.setStyle("skinClass", SkinDropDownList);
         }
      }
                 
      private function onComBoxIndexChange(event:IndexChangeEvent):void{
        if (event.newIndex < 0){
          if(this.textInput)
           this.textInput.text = promptText;
           Alert.show("Typed item is not present in list","Warning");
        }
      }
]]>
fx:Script>
s:ComboBox>

Step 2: - Create combobox skin named as SkinComboBox.

Step 3: - Create DropDownList skin as SkinDropDownList
      In SkinDropDownList skin Class remove Label and replace TextInput.

Ex. as below: -

id="textInput" borderAlpha="0" borderVisible="false"
mouseEnabled="false" mouseChildren="false" editable="false" selectable="false" left="7" right="30" top="2" bottom="2" width="75" verticalCenter="1" contentBackgroundAlpha="0" color="0x000000" />

Solution: -
You have to change skin at run time on condition. Here I have created useAsDropDown property which will define which component you want to show i.e. ComboBox or DropDownList.