Гибкое средство визуализации пользовательских элементов для отображаемого элемента в выпадающем списке - PullRequest
8 голосов
/ 06 ноября 2008

Я использую средство визуализации пользовательских элементов в выпадающем списке для отображения пользовательского чертежа вместо текстовой метки по умолчанию.

Это хорошо работает для выпадающего списка, но отображаемый элемент (когда список закрыт) все еще является текстовым представлением моего объекта.

Можно ли отобразить отображаемый элемент так же, как в раскрывающемся списке?

Ответы [ 6 ]

9 голосов
/ 11 ноября 2008

По умолчанию вы не можете сделать это. Однако, если вы расширяете ComboBox, вы можете легко добавить эту функцию. Вот краткий пример, это грубая версия, и, вероятно, она нуждается в тестировании / настройке, но она показывает, как этого можно добиться.

package
{
    import mx.controls.ComboBox;
    import mx.core.UIComponent;

    public class ComboBox2 extends ComboBox
    {
        public function ComboBox2()
        {
            super();
        }

        protected var textInputReplacement:UIComponent;

        override protected function createChildren():void {
            super.createChildren();

            if ( !textInputReplacement ) {
                if ( itemRenderer != null ) {
                    //remove the default textInput
                    removeChild(textInput);

                    //create a new itemRenderer to use in place of the text input
                    textInputReplacement = itemRenderer.newInstance();
                    addChild(textInputReplacement);
                }
            }
        }

        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
            super.updateDisplayList(unscaledWidth, unscaledHeight);

            if ( textInputReplacement ) {
                textInputReplacement.width = unscaledWidth;
                textInputReplacement.height = unscaledHeight;
            }
        }
    }
}
5 голосов
/ 23 ноября 2009

Я попробовал вышеуказанное решение, но обнаружил, что selectedItem не отображается, когда выпадающий список закрыт. Чтобы связать свойство данных itemRenderer с selectedItem, потребовалась дополнительная строка кода:

            if ( !textInputReplacement ) {
                    if ( itemRenderer != null ) {
                            //remove the default textInput
                            removeChild(textInput);

                            //create a new itemRenderer to use in place of the text input
                            textInputReplacement = itemRenderer.newInstance();

                            // ADD THIS BINDING:
                            // Bind the data of the textInputReplacement to the selected item
                            BindingUtils.bindProperty(textInputReplacement, "data", this, "selectedItem", true);

                            addChild(textInputReplacement);
                    }
            }
3 голосов
/ 26 июля 2012

Я расширил код Дейна немного дальше. В некоторых случаях нажатие не открывало выпадающее окно с моим рендерером, и я заметил, что обычные скины Flex ComboBox не запускаются. Таким образом, в replaceTextInput () я добавил несколько дополнительных прослушивателей событий и сохранил ссылку на кнопку ComboBox, используемую для отображения скинов. Теперь он ведет себя так же, как обычный ComboBox.

Вот код:

    package
    {
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.events.MouseEvent;

    import mx.binding.utils.BindingUtils;
    import mx.controls.Button;
    import mx.controls.ComboBox;
    import mx.core.IFactory;
    import mx.core.UIComponent;
    import mx.events.DropdownEvent;

    /**
     * Extension of the standard ComboBox that will use the assigned 'itemRenderer'
     * for both the list items and the selected item.
     * 
     * Based on code from:
     * /230805/gibkoe-sredstvo-vizualizatsii-polzovatelskih-elementov-dlya-otobrazhaemogo-elementa-v-vypadayschem-spiske
     */
    public class ComboBoxFullRenderer extends ComboBox
    {
    protected var textInputReplacement:UIComponent;
    private var _increaseW:Number = 0;
    private var _increaseH:Number = 0;


    /**
     * Keeps track of the current open/close state of the drop down list. 
     */
    protected var _isOpen:Boolean = false;

    /**
     * Stores a reference to the 'Button' which overlays the ComboBox.  Allows
     * us to pass events to it so skins are properly triggered. 
     */
    protected var _buttonRef:Button = null;


    /**
     * Constructor. 
     */
    public function ComboBoxFullRenderer() {
        super();
    }


    /**
     * Sets a value to increase the width of our ComboBox to adjust sizing. 
     * 
     * @param val Number of pixels to increase the width of the ComboBox.
     */
    public function set increaseW(val:Number):void {
        _increaseW = val;
    }

    /**
     * Sets a value to increase the height of our ComboBox to adjust sizing. 
     * 
     * @param val Number of pixels to increase the height of the ComboBox.
     */
    public function set increaseH(val:Number):void {
        _increaseH = val;
    }


    /**
     * Override the 'itemRenderer' setter so we can also replace the selected
     * item renderer.
     *  
     * @param value The renderer to be used to display the drop down list items
     *   and the selected item.
     */
    override public function set itemRenderer(value:IFactory):void {
        super.itemRenderer = value;
        replaceTextInput();
    }


    /**
     * Override base 'createChildren()' routine to call our 'replaceTextInput()'
     * method to replace the standard selected item renderer.
     *  
     * @see #replaceTextInput();
     */
    override protected function createChildren():void {
        super.createChildren();
        replaceTextInput();
    }


    /**
     * Routine to replace the ComboBox 'textInput' child with our own child
     * that will render the selected data element.  Will create an instance of
     * the 'itemRenderer' set for this ComboBox. 
     */
    protected function replaceTextInput():void {
        if ( !textInputReplacement ) {
            if ( this.itemRenderer != null && textInput != null ) {
                //remove the default textInput
                removeChild(textInput);

                //create a new itemRenderer instance to use in place of the text input
                textInputReplacement = this.itemRenderer.newInstance();
                // Listen for clicks so we can open/close the drop down when
                // renderer components are clicked.  
                textInputReplacement.addEventListener(MouseEvent.CLICK, _onClick);
                // Listen to the mouse events on our renderer so we can feed them to
                // the ComboBox overlay button.  This will make sure the button skins
                // are activated.  See ComboBox::commitProperties() code.
                textInputReplacement.addEventListener(MouseEvent.MOUSE_DOWN, _onMouseEvent);
                textInputReplacement.addEventListener(MouseEvent.MOUSE_UP, _onMouseEvent);
                textInputReplacement.addEventListener(MouseEvent.ROLL_OVER, _onMouseEvent);
                textInputReplacement.addEventListener(MouseEvent.ROLL_OUT, _onMouseEvent);
                textInputReplacement.addEventListener(KeyboardEvent.KEY_DOWN, _onMouseEvent);

                // Bind the data of the textInputReplacement to the selected item
                BindingUtils.bindProperty(textInputReplacement, "data", this, "selectedItem", true);

                // Add our renderer as a child.
                addChild(textInputReplacement);

                // Listen for open close so we can maintain state.  The
                // 'isShowingDropdown' property is mx_internal so we don't
                // have access to it. 
                this.addEventListener(DropdownEvent.OPEN, _onOpen);
                this.addEventListener(DropdownEvent.CLOSE, _onClose);

                // Save a reference to the mx_internal button for the combo box.
                //  We will need this so we can call its dispatchEvent() method.
                for (var i:int = 0; i < this.numChildren; i++) {
                    var temp:Object = this.getChildAt(i);
                    if (temp is Button) {
                        _buttonRef = temp as Button;
                        break;
                    } 
                }
            }
        }
    }


    /**
     * Detect open events on the drop down list to keep track of the current
     * drop down state so we can react properly to a click on our selected
     * item renderer.
     *  
     * @param event The DropdownEvent.OPEN event for the combo box.
     */
    protected function _onOpen(event:DropdownEvent) : void {
        _isOpen = true;
    }


    /**
     * Detect close events on the drop down list to keep track of the current
     * drop down state so we can react properly to a click on our selected
     * item renderer.
     *  
     * @param event The DropdownEvent.CLOSE event for the combo box.
     */
    protected function _onClose(event:DropdownEvent) : void {
        _isOpen = false;
    }


    /**
     * When we detect a click on our renderer open or close the drop down list
     * based on whether the drop down is currently open/closed.
     *  
     * @param event The CLICK event from our selected item renderer.
     */
    protected function _onClick(event:MouseEvent) : void {
        if (_isOpen) {
            this.close(event);
        } else {
            this.open();
        }
    }


    /**
     * React to certain mouse/keyboard events on our selected item renderer and
     * pass the events to the ComboBox 'button' so that the skins are properly
     * applied.
     *  
     * @param event A mouse or keyboard event to send to the ComboBox button.
     * 
     */
    protected function _onMouseEvent(event:Event) : void {
        if (_buttonRef != null) {
            _buttonRef.dispatchEvent(event);
        }
    }
    } // end class
    } // end package
0 голосов
/ 10 сентября 2015

Я нашел более простой способ изменения рендера для выбранного элемента. Этот работает, только если ваш элемент наследуется от класса TextInput, во Flex 4.0 или выше.

В Flex v4.5, в ComboBase.createChildren в строке 1177, вы обнаружите, что класс, определяемый для textInput, можно передать с помощью клавиши стиля textInputClass:

// Mechanism to use MXFTETextInput. 
var textInputClass:Class = getStyle("textInputClass");            
if (!textInputClass || FlexVersion.compatibilityVersion < FlexVersion.VERSION_4_0)
{
    textInput = new TextInput();
}
else
{
   textInput = new textInputClass();
}

Просто измените значение этого ключа в конструкторе вашей комбо, и теперь у вас есть собственный рендер для selectedItem.

public function ComboAvailableProfessor()
{
    super();

    itemRenderer = new ClassFactory( ProfessorAvailableListItemRenderer );
    setStyle( 'textInputClass', ProfessorAvailableSelectedListItemRenderer );
}

Наконец, вы должны привязать свойство data к свойству selectedItem в вашем комбо, чтобы отобразить данные.

override protected function createChildren():void
{
    super.createChildren();

    BindingUtils.bindProperty( textInput, 'data', this, 'selectedItem', true );
}
0 голосов
/ 12 октября 2011

Я искал способ сделать это с помощью Spark ComboBox.

Этот поток был очень полезен для меня, но до сих пор были только ответы о том, как это сделать с помощью mx: ComboBox. Я подумал, что должен добавить свой ответ о том, как это сделать с помощью искры ComboBox.

  1. Создать новый скин ComboBox
  2. Скрыть и отключить ввод текста
  3. Вставьте свой собственный компонент

Вот как будет выглядеть скин:

<s:SparkSkin>

    <... Lots of other stuff/>

    <s:BorderContainer height="25">
        <WHATEVER YOU NEED HERE!/>
    </s:BorderContainer>

    <!-- Disable the textInput and hide it -->
    <s:TextInput id="textInput"
        left="0" right="18" top="0" bottom="0" 
        skinClass="spark.skins.spark.ComboBoxTextInputSkin"

        visible="false" enabled="false"/> 


</s:SparkSkin>

С помощью Spark ComboBox этот процесс очень прост и не требует расширения ComboBox.

0 голосов
/ 15 марта 2010

Спасибо, Маклема и Мауриц де Бур. Я добавил еще пару вещей в этот класс, чтобы он соответствовал моим потребностям:

  • Я переопределил set itemRenderer, чтобы это работало, если вы устанавливаете itemRenderer через AS вместо mxml. Я переместил код замены ввода текста в его собственную функцию, чтобы избежать дублирования.

  • Я добавил сеттеры для увеличения и увеличения, чтобы изменить размер комбобокса, если необходимо, потому что мой рендер вначале был слишком большим для комбобокса.

  • Я вычел 25 из ширины textInputReplacement, чтобы она никогда не перекрывала выпадающую кнопку ... может быть лучше использовать что-то более пропорциональное для размещения различных скинов и тому подобное.

Код:

package
{
 import mx.binding.utils.BindingUtils;
 import mx.controls.ComboBox;
 import mx.core.IFactory;
 import mx.core.UIComponent;

    public class ComboBox2 extends ComboBox
    {
        public function ComboBox2()
        {
                super();
        }

        protected var textInputReplacement:UIComponent;
        private var _increaseW:Number = 0;
        private var _increaseH:Number = 0;

  public function set increaseW(val:Number):void
  {
   _increaseW = val;
  }

  public function set increaseH(val:Number):void
  {
   _increaseH = val;
  }

  override public function set itemRenderer(value:IFactory):void
  {
   super.itemRenderer = value;
   replaceTextInput();
  }

        override protected function createChildren():void 
        {
                super.createChildren();
    replaceTextInput();

        }

        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {

          unscaledWidth += _increaseW;
          unscaledHeight += _increaseH;

                super.updateDisplayList(unscaledWidth, unscaledHeight);

                if ( textInputReplacement ) {
                        textInputReplacement.width = unscaledWidth - 25;
                        textInputReplacement.height = unscaledHeight;
                }
        }

        protected function replaceTextInput():void
        {
         if ( !textInputReplacement ) {
                        if ( this.itemRenderer != null ) {
                                //remove the default textInput
                                removeChild(textInput);

                                //create a new itemRenderer to use in place of the text input
                                textInputReplacement = this.itemRenderer.newInstance();
                                addChild(textInputReplacement);

                                // ADD THIS BINDING:
                             // Bind the data of the textInputReplacement to the selected item
                             BindingUtils.bindProperty(textInputReplacement, "data", this, "selectedItem", true);

                             addChild(textInputReplacement);

                        }
                }
        }
    }
}
...