Search code examples
actionscript-3apache-flexlistflex4.5itemrenderer

Disable CTRL pression for selection multiple values in list


I have a custom itemrenderer for Spark.List

<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                xmlns:s="library://ns.adobe.com/flex/spark"
                xmlns:mx="library://ns.adobe.com/flex/mx"
                autoDrawBackground="true">
    <s:states>
        <s:State name="normal"/>
        <s:State name="selected"/>
        <s:State name="hovered"/>
    </s:states>
    <s:CheckBox label="{data.name}" selected.selected="true" selected.normal="false"/>

</s:ItemRenderer>

The list:

        private function get UOAbilitate():List
        {
            var l:List = new List();
            l.dataProvider = listaUOA;
            l.allowMultipleSelection = true;                
            l.itemRenderer = new ClassFactory(CheckBoxItemRenderer);
            return l;                   
        }
        [Bindable]private var listaUOA:ArrayCollection = new ArrayCollection([
                {name: "Uo1"},
                {name: "Uo2"},
                {name: "Uo3"},
                {name: "Uo4"},
                {name: "Uo5"},
                {name: "Uo6"},
                {name: "Uo7"},
                {name: "Uo8"},
                {name: "Uo9"},
                {name: "Uo10"},
                {name: "Uo11"},
                {name: "Uo12"}
            ]);     

The checkboxes behave in the correct way. if I have selected one value then selecting another one will result in select the new one and deselect the older..

Using CTRL both items remain selected..I will obtain the same result without the need to press the ctrl key...


Solution

  • The easiest way to do this is to create a subclass of List like this:

    public class MyList extends List {
    
        public function MyList() {
            allowMultipleSelection = true;
        }
    
        override protected function item_mouseDownHandler(event:MouseEvent):void {
            event.ctrlKey = true;
            super.item_mouseDownHandler(event);
        }
    
    }
    

    We set allowMultipleSelection to true by default (the default value for the List component is false), and we intercept the MouseEvent.MOUSE_DOWN so that we can fool the List into thinking that the CTRL key is always pressed.

    If you're looking for a similar behaviour for the DataGrid class, read this answer: SelectItem Method in spark Datagrid?

    Note: for the list of CheckBoxes situation, I've created a reusable custom component called CheckBoxGroup that does this and also assigns the CheckBoxItemRenderer by default. That way I don't have to do this over and over again. (It also does some other custom stuff, like selecting all the boxes at once, but that's off topic here).