0

可能这很简单,但现在我无法为它提出解决方案。这是我的问题的简要描述:

我有一本剪贴画对象字典:

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

猫.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>

谁能建议我一个解决方案或任何想法以任何不同的方式实施它?谢谢。

4

2 回答 2

3

您在该字典中放入的是类引用而不是实例。您必须创建所需图形的实例才能将其添加到 displayList。因此,有两种方法可以解决您的问题。

方法一

将 Graphics 的实例放入 Dictionary 中(而不是 Class 引用):

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

然后只需将其添加到 displayList 中:

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

方法二

动态创建 Class 引用的实例。我们保持字典原样:

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

并创建一个实例并将其添加到 displayList 中,如下所示:

var Graphic:Class = clipartDict[(data as ClipArtVO).clipArtFileName];
addElement(new Graphic());
于 2012-06-07T11:37:13.223 回答
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);
}
于 2012-06-07T11:32:20.737 回答