2012-06-07 25 views
0

可能這是非常簡單的,但現在我無法爲它提供解決方案。這裏是我的問題的簡要說明:如何在運行時向itemrenderer添加'Graphic'?

我有剪貼畫對象的字典爲:

clipartDict['cat'] = Cat; //Cat.mxml 
clipartDict['dog'] = Dog; //Dog.mxml 

Cat.mxml:

<s:Graphic> 
    <s:Path x="2.86723" y="-0.000106812" data="M3.45943 80.3419C3.06051 77.3605 0.002399> 
    </s:Path> 
</s:Graphic> 

MyView.mxml(相關代碼):

<s:SkinnableDataContainer width="300" dataProvider="{clipArts}"> 
    <s:layout> 
     <s:TileLayout requestedColumnCount="1"/> 
    </s:layout> 
    <s:itemRenderer> 
     <fx:Component> 
      <s:ItemRenderer> 
       <fx:Script> 
        <![CDATA[ 
         import models.vo.ClipArtVO; 
         // (data as ClipArtVO).clipArtFileName represents the 'key' in dictionary. 
         // Now, how can I display the relevent clipart from dict based on the key 
         // this.addElement throws an Type Coercion error 

        ]]> 
       </fx:Script> 

      </s:ItemRenderer> 
     </fx:Component> 
    </s:itemRenderer> 
</s:SkinnableDataContainer> 

任何人都可以建議我一個解決方案或任何想法以任何不同的方式來實現它? 謝謝。

回答

3

你在該詞典中放入的是類引用,而不是實例。您必須創建所需圖形的實例以將其添加到displayList。所以有兩種方法可以解決您的問題。

方法1

在詞典圖形(而不是類的引用)的穿戴實例:

clipartDict['cat'] = new Cat(); 
clipartDict['dog'] = new Dog(); 

然後,只需將它添加到顯示列表:

var graphic:Graphic = clipartDict[(data as ClipArtVO).clipArtFileName]; 
addElement(graphic); 

方法2

即時創建類引用的實例。我們保留了字典,因爲它是:

clipartDict['cat'] = Cat; 
clipartDict['dog'] = Dog; 

,並創建一個實例,並將其添加到顯示列表如下:

var Graphic:Class = clipartDict[(data as ClipArtVO).clipArtFileName]; 
addElement(new Graphic()); 
+0

謝謝你。你拯救了我的一天。從來沒有注意到字典中的類被引用而不是實例。乾杯!! –

0

您應該可以將您的cat.mxml文件包裝在SpriteVisualElement中。這有點乏味,但基本上這樣做:

protected var sprite :SpriteVisualElement; 
protected var class : Class; 
protected var graphicInstance : Graphic; 

protected function dataChangeMethod():void{ 
    // (data as ClipArtVO).clipArtFileName represents the 'key' in dictionary. 
    // You told us about the key, but not the value. I'm assuming the value is an actual class 
    // and not an instance of the class 
    class = (data as ClipArtVO).clipArtFileName; 
    // create an instance of the class 
    graphicInstance = new class(); 
    // create the new spriteVisualElement instance 
    sprite = new SpriteVisualElement(); 
    // Add the graphic instance as a child to the spriteVisualElement 
    // you may need to do any sizing of the graphicInstance before adding it 
    sprite.addChild(graphicInstance); 
    // add the Sprite Visual Element as a child to your container 
    this.addElement(sprite); 
} 
+1

我想'SpriteVisualElement'是多餘的:'Graphic'實現'IVisualElement' 。 – RIAstar

+0

@RIAstar你是對的;我的錯。 MX Graphic標籤擴展了實現IVisualElement的UIComponent。我的示例適用於FXG元素,但MXML圖形應該不需要額外的類。我不清楚爲什麼原始海報有一個類型coercian錯誤。 – JeffryHouser