可能这很简单但是现在我无法为它提供解决方案。以下是我的问题的简要说明:
我有一个剪贴画对象字典:
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>
有人能建议我以任何不同的方式实施解决方案或任何想法吗? 感谢。
答案 0 :(得分:3)
您在该词典中添加的是类引用,而不是实例。您必须创建所需Graphic的实例才能将其添加到displayList。因此,有两种方法可以解决您的问题。
方法1
将Graphics的实例放在Dictionary中(而不是Class引用):
clipartDict['cat'] = new Cat();
clipartDict['dog'] = new Dog();
然后只需将其添加到displayList:
var graphic:Graphic = clipartDict[(data as ClipArtVO).clipArtFileName];
addElement(graphic);
方法2
动态创建Class引用的实例。我们保持字典原样:
clipartDict['cat'] = Cat;
clipartDict['dog'] = Dog;
并创建一个实例并将其添加到displayList中,如下所示:
var Graphic:Class = clipartDict[(data as ClipArtVO).clipArtFileName];
addElement(new Graphic());
答案 1 :(得分: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);
}