проблема с чекбоксом datarenderer - PullRequest
0 голосов
/ 27 июля 2011

Пожалуйста, проверьте код ниже: userinfo.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="init();">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
        <!--Validation Start-->
        <mx:StringValidator source="{userNameInput}" property="text" 
                            requiredFieldError="Please enter only string"/>
        <mx:StringValidator source="{locationInput}" property="text" 
                            requiredFieldError="Please enter only string"/>
        <mx:Validator source="{genderfield}" property="selectedValue" 
                      triggerEvent="change" 
                      requiredFieldError="One Option must be selected"
                      listener="{wrapper}"/>
    </fx:Declarations>
    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.controls.Alert;
            import mx.events.ItemClickEvent;
            import mx.events.ListEvent;
            import mx.utils.ObjectUtil;


            private var mySO:SharedObject;
            private var _objValidation:ValidationField;
            [Bindable]public var dgItems:ArrayCollection = new ArrayCollection();

            public function init():void{
                _objValidation = new ValidationField();
                mySO = SharedObject.getLocal("newData","/");
                if(mySO.data.info != null){
                    dgItems = mySO.data.info;
                }
                addbtn.label = "Add";
                addbtn.addEventListener(MouseEvent.CLICK, call);
            }

            public function resetForm():void{
                userNameInput.text = "";
                locationInput.text = "";
                genderfield.selection = null;
                userNameInput.errorString = "";
                locationInput.errorString = "";
            }

            public function addItem():void{
                if(userNameInput.text != "" && locationInput.text != "" && genderfield.selection != null){
                    dgItems.addItem({name:userNameInput.text,location:locationInput.text,gender:genderfield.selectedValue});
                    resetForm();
                }
            }
            public function savaData():void{
                mySO.data.info = dgItems;
                mySO.flush();
            }

            public function deleteRow():void{
                while(datagrid.selectedItem != null){
                    dgItems.removeItemAt(datagrid.selectedIndex);
                }  
                     addbtn.label = "Add";
                     resetForm();
            }

            public function dgChangeHandler():void{
                addbtn.label = "Edit";
                resetForm();
                userNameInput.text = datagrid.selectedItem.name;
                locationInput.text = datagrid.selectedItem.location;
                genderfield.selectedValue = datagrid.selectedItem.gender;
            }

            public function call(event:Event):void{
                if(event.currentTarget.label == "Add"){
                    addItem();
                }
                else if(event.currentTarget.label == "Edit"){
                    editRow();
                }
                addbtn.label = "Add";
                resetForm();
            }

            public function editRow():void{
                if(datagrid.selectedItem != null){
                    dgItems.setItemAt({name:userNameInput.text,location:locationInput.text,gender:genderfield.selectedValue},datagrid.selectedIndex);
                    resetForm();
                }
            }
        ]]>
    </fx:Script>
    <mx:Form x="250">
        <mx:FormHeading label="User Information" fontWeight="bold"/>
        <mx:FormItem required="true" label="UserName" fontWeight="bold">
            <s:TextInput id="userNameInput" restrict="A-Z a-z"/>
        </mx:FormItem>
        <mx:FormItem required="true" label="Location" fontWeight="bold">
            <s:TextInput id="locationInput" restrict="A-Z a-z"/>
        </mx:FormItem>
        <mx:FormItem required="true" label="Gender" fontWeight="bold" width="210">
            <mx:HBox id="wrapper">
                <s:RadioButtonGroup id="genderfield"/>
                <s:RadioButton label="Male" groupName="genderfield"/>
                <s:RadioButton label="Female" groupName="genderfield"/>
            </mx:HBox>
        </mx:FormItem>
        <mx:FormItem>
            <mx:HBox>
                <mx:Button id="addbtn"/>
                <mx:Button label="Reset" click="resetForm();"/>
            </mx:HBox>
        </mx:FormItem>
    </mx:Form>
        <mx:DataGrid id="datagrid" x="550" y="20" dataProvider="{dgItems}" change="dgChangeHandler();">
            <mx:columns>
                <mx:DataGridColumn headerText="Visible" dataField="shouldDelete" textAlign="center" itemRenderer="CheckBoxRenderer">
                </mx:DataGridColumn>
                <mx:DataGridColumn headerText="UserName" dataField="name" textAlign="center"/>
                <mx:DataGridColumn headerText="Location" dataField="location" textAlign="center"/>
                <mx:DataGridColumn headerText="Gender" dataField="gender" textAlign="center"/>
            </mx:columns>
        </mx:DataGrid>
        <mx:HBox x="650" y="250" horizontalGap="30">
            <s:Button label="Delete" click="deleteRow();"/>
            <s:Button label="Save" click="savaData();"/>
        </mx:HBox>


</s:Application>

и checkboxRenderer.mxml

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

    import mx.containers.HBox;
    import mx.controls.Alert;
    import mx.controls.CheckBox;

    public class CheckBoxRenderer extends HBox
    {
        private var cb:CheckBox;

        public function CheckBoxRenderer()
        {
            super();
            cb.addEventListener(MouseEvent.CLICK, changeState);
        }

        public function changeState(event:Event):void{

        }
        override public function set data(value:Object):void{
            if(value!=null){
                super.data = value;
                removeAllChildren();
                cb = new CheckBox();
                addChild(cb);
                cb.visible = true;
                if(false){
                    cb.selected = true;
                    Alert.show("checkbox selected");
                }
                else{
                    cb.selected = false;
                    Alert.show("Checkbox unselected");
                }
                setStyle("verticleAlign","middle");
                setStyle("textAlign","center");
                setStyle("horizontalCenter","center");
            }
        }
    }
}

Может кто-нибудь сказать, почему я не могу установить значение флажка? и когда я установил флажок, а затем снял этот флажок, я не могу вернуться в состояние кнопки «Добавить».

1 Ответ

0 голосов
/ 27 июля 2011

Модификация:

  1. Userinfo.mxml: изменения в dgChangeHandler: Добавлено событие, добавлена ​​проверка:
  2. CheckBoxRenderer.as: логика создания флажка написана в конструкторе, флажок включить отключить предупреждение перемещено в методе changeState

Проверьте этот обновленный код: [userinfo.mxml]

<?xml version="1.0" encoding="utf-8"?> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"  
xmlns:mx="library://ns.adobe.com/flex/mx" 
minWidth="955" minHeight="600" creationComplete="init();">     
<fx:Declarations>        
<!-- Place non-visual elements (e.g., services, value objects) here -->     
    <!--Validation Start-->    
    <mx:StringValidator source="{userNameInput}" property="text" requiredFieldError="Please enter only string"/> 
    <mx:StringValidator source="{locationInput}" property="text" 
                        requiredFieldError="Please enter only string"/>  
    <mx:Validator source="{genderfield}" property="selectedValue"      
                  triggerEvent="change"                      
                  requiredFieldError="One Option must be selected"   
                  listener="{wrapper}"/>  
</fx:Declarations>   
<fx:Script>        
    <![CDATA[      
        import mx.collections.ArrayCollection;
        import mx.controls.Alert;
        import mx.events.ItemClickEvent;
        import mx.events.ListEvent;
        import mx.utils.ObjectUtil;          
        private var mySO:SharedObject;      

        [Bindable]
        public var dgItems:ArrayCollection = new ArrayCollection(); 

        public function init():void{             
            mySO = SharedObject.getLocal("newData","/");   
            if(mySO.data.info != null){               
                dgItems = mySO.data.info;              
            }                 addbtn.label = "Add";     
            addbtn.addEventListener(MouseEvent.CLICK, call);  
        }           

        public function resetForm():void
        {       
            userNameInput.text = "";            
            locationInput.text = "";            
            genderfield.selection = null;        
            userNameInput.errorString = "";          
            locationInput.errorString = "";        
        } 

        public function addItem():void
        {                
            if(userNameInput.text != "" && locationInput.text != "" && genderfield.selection != null)
            {                     
                dgItems.addItem({name:userNameInput.text,location:locationInput.text,gender:genderfield.selectedValue}); 
                resetForm();       
            }             
        }   

        public function savaData():void
        {              
            mySO.data.info = dgItems;  
            mySO.flush();        
        }     

        public function deleteRow():void
        {             
            while(datagrid.selectedItem != null)
            {                 
                dgItems.removeItemAt(datagrid.selectedIndex);   
            }                       
            addbtn.label = "Add";   
            resetForm();           
        }    

        public function dgChangeHandler(event:ListEvent):void
        {               
            if(event.itemRenderer is CheckBoxRenderer)
            {
                addbtn.label = "Add";   
                resetForm();
                return;
            }
            addbtn.label = "Edit";    
            resetForm();          
            userNameInput.text = datagrid.selectedItem.name; 
            locationInput.text = datagrid.selectedItem.location;  
            genderfield.selectedValue = datagrid.selectedItem.gender;  
        }    

        public function call(event:Event):void
        {                
            if(event.currentTarget.label == "Add")
            {                     
                addItem();              
            }                 
            else if(event.currentTarget.label == "Edit")
            {                    
                editRow();         
            }                
            addbtn.label = "Add";  
            resetForm();           
        }   

        public function editRow():void
        {               
            if(datagrid.selectedItem != null)
            {                   
                dgItems.setItemAt({name:userNameInput.text,location:locationInput.text,gender:genderfield.selectedValue},datagrid.selectedIndex);   
                resetForm(); 
            }            
        }        

    ]]>    
</fx:Script> 
<mx:Form x="250">   
    <mx:FormHeading label="User Information" fontWeight="bold"/>  
    <mx:FormItem required="true" label="UserName" fontWeight="bold"> 
        <s:TextInput id="userNameInput" restrict="A-Z a-z"/>        
    </mx:FormItem>   
    <mx:FormItem required="true" label="Location" fontWeight="bold"> 
        <s:TextInput id="locationInput" restrict="A-Z a-z"/>       
    </mx:FormItem>      
    <mx:FormItem required="true" label="Gender" fontWeight="bold" width="210">  
        <mx:HBox id="wrapper">            
            <s:RadioButtonGroup id="genderfield"/>  
            <s:RadioButton label="Male" groupName="genderfield"/>  
            <s:RadioButton label="Female" groupName="genderfield"/> 
        </mx:HBox>       
    </mx:FormItem>        
    <mx:FormItem>          
        <mx:HBox>         
            <mx:Button id="addbtn"/>  
            <mx:Button label="Reset" click="resetForm();"/>     
        </mx:HBox>      
    </mx:FormItem>    
</mx:Form>       
<mx:DataGrid id="datagrid" x="550" y="20" dataProvider="{dgItems}" change="dgChangeHandler(event)"> 
    <mx:columns>              
        <mx:DataGridColumn headerText="Visible" dataField="shouldDelete" textAlign="center" itemRenderer="CheckBoxRenderer">               
        </mx:DataGridColumn>  
        <mx:DataGridColumn headerText="UserName" dataField="name" textAlign="center"/>    
        <mx:DataGridColumn headerText="Location" dataField="location" textAlign="center"/> 
        <mx:DataGridColumn headerText="Gender" dataField="gender" textAlign="center"/>      
    </mx:columns>        
</mx:DataGrid>       
<mx:HBox x="650" y="250" horizontalGap="30">    
    <s:Button label="Delete" click="deleteRow();"/>  
    <s:Button label="Save" click="savaData();"/>      
</mx:HBox>   
</s:Application> 

Файл: [CheckBoxRenderer.as]

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

import mx.containers.HBox;
import mx.controls.Alert;
import mx.controls.CheckBox;

public class CheckBoxRenderer extends HBox  
{         
    private var cb:CheckBox;         
    public function CheckBoxRenderer()     
    {           
        super();
        removeAllChildren();             
        cb = new CheckBox();              
        addChild(cb);               
        cb.visible = true;
        cb.addEventListener(MouseEvent.CLICK, changeState); 
        setStyle("verticleAlign","middle");   
        setStyle("textAlign","center");       
        setStyle("horizontalCenter","center");  
    }          
    public function changeState(event:Event):void
    {   
        if(cb.selected)
        {
            Alert.show("checkbox selected");
        }
        else
        {
            Alert.show("Checkbox unselected");     
        }
    }
    override public function set data(value:Object):void
    { 
        if(value!=null)
        {                 
            super.data = value;     
            if(false)
            {                   
                cb.selected = true;     
            }
            else
            {                 
                cb.selected = false;            
            }                
        }
    }     
} 
}
...