Candy Chiu
Candy Chiu

Reputation: 6679

Flex Spark DropDownList selectedItem didn't update after dataProvider changed

I have two dataProvider's for one DropDownList. The following code can be compiled and run.

<?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"
   creationComplete="flipLast()"
   minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
     import mx.collections.ArrayCollection;
     public function flipLast():void {
          if( last ) {
               list.dataProvider = dp1;
               list.selectedItem = "Flex";
          } else {
               list.dataProvider = dp2;
               list.selectedItem = "Catalyst";        
          }
          last = !last;
     }

     public var last:Boolean = true;
     public var dp1:ArrayCollection = new ArrayCollection( [ "Flex", "Air" ] );
     public var dp2:ArrayCollection = new ArrayCollection( [ "Catalyst", "FlashBuilder" ] );
]]>
</fx:Script>

<s:VGroup>
     <s:DropDownList id="list" requireSelection="true" />

     <s:Label id="listSelectedItem" text="{list.selectedItem}" />
     <s:Label id="listSelectedIndex" text="{list.selectedIndex}" />

     <s:Button label="Flip" click="flipLast()" />
</s:VGroup>
</s:Application>

Scenario 1: dataProvider updated, but selectedIndex is the same. At startup: [ listSelectedItem=Flex, listSelectedIndex=1 ]. Click Flip: dataProvider is updated, but still [ listSelectedItem=Flex, listSelectedIndex=1 ].

Scenario 2: dataProvider updated, selectedIndex is also updated. At startup: [ listSelectedItem=Flex, listSelectedIndex=1 ]. Select Air from list: [ listSelectedItem=Air, listSelectedIndex=2 ]. Click Flip: dataProvider is updated, but still [ listSelectedItem=Catalyst, listSelectedIndex=1 ].

Seems to me that selectedItem is driven by selectedIndex. selectedItem updates only when selectedIndex updates. Shouldn't selectedItem be updated when dataProvider is updated? Is binding to selectedItem flawed?

Upvotes: 2

Views: 5677

Answers (1)

NielsBjerg
NielsBjerg

Reputation: 701

Perhaps you are right in assuming it is broken.. I won't judge on that. The fix for your problem is pretty simple though, change the flip function to reset selected index, thereby triggering data-change on the list, and eventually binding on your components:

public function flipLast():void {
          list.selectedIndex = -1;
          if( last ) {
               list.dataProvider = dp1;
               list.selectedItem = "Flex";
          } else {
               list.dataProvider = dp2;
               list.selectedItem = "Catalyst";        
          }
          last = !last;
     }

Upvotes: 2

Related Questions