2012-02-08 59 views
1

我無法將spark的DropDownList的selectedIndex公共屬性綁定到它在視圖的演示模型中的原始源。無法將DropDownList的selectedIndex綁定到Bindable類的selectedIndex成員

爲了複製這個問題儘可能少的行,我有兩個視圖和一個演示模型。代碼如下。

Main.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" 
       xmlns:views="com.blah.views.*"> 

    <views:DropDownListView/> 

</s:Application> 

DropDownListView.mxml

<?xml version="1.0" encoding="utf-8"?> 
<s:Group 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="400" height="300"> 

    <fx:Script> 
     <![CDATA[ 
      import com.blah.presentationmodels.DropDownListPresentationModel; 

      [Bindable] 
      private var pm:DropDownListPresentationModel = new DropDownListPresentationModel(); 
     ]]> 
    </fx:Script> 

    <s:DropDownList id="myDropDownList" 
        dataProvider="{pm.list}" 
        selectedIndex="{pm.selectedIndex}" 
        valueCommit="{pm.selectionChanged()}"/> 

</s:Group> 

DropDownListPresentationModel.as

package com.blah.presentationmodels 
{ 
    import mx.collections.ArrayCollection; 

    [Bindable] 
    public class DropDownListPresentationModel 
    { 
     public var selectedIndex:int = -1; 
     public var list:ArrayCollection = new ArrayCollection(); 

     public function DropDownListPresentationModel() 
     { 
      list.addItem("Load of Bread"); 
      list.addItem("Stick of Butter"); 
      list.addItem("Carton of Milk"); 
     } 

     public function selectionChanged():void 
     { 
      var newSelectedIndex:int = selectedIndex; // always -1 
     } 
    } 
} 

調試應用程序我發現,無論從DropDownList中選擇哪個項目,呈現模型中的selectedIndex始終保持指定的默認值。對於上面的示例代碼,這是-1。

如何在演示模型中綁定selectedIndex,以便在所選項目DropDownList更改時進行適當更新?

回答

4

調試我發現的selectedIndex在 演示模型總是停留在我從DropDownList中選擇分配 無論哪個項目的默認值應用。對於上面的 示例代碼,這是-1。

根據您提供的代碼,這是正確的。您已將pm.selectedIndex綁定到myDropDownList.selectedIndex。所以,每當pm.selectedIndex發生變化,myDropDownList.selectedIndex的值就會改變。

你還沒有做的是將myDropDownList.selectedIndex綁定到pm.selectedIndex。因此,對myDropDownList.selectedIndex所做的任何更改都不會對pm.selectedIndex產生影響。最簡單的方法,使這種「綁定」兩種方式工作是使用簡寫MXML語法:

<s:DropDownList id="myDropDownList" 
       selectedIndex="@{pm.selectedIndex}" /> 

More information on that in the docs,其中也包括了「預Flex 4的」另類它是使用綁定標籤:

<mx:Binding source="myDropDownList.selectedIndex" destination="pm.selectedIndex"/> 
相關問題