如何在运行时在 Flex 中获取 BorderContainer 的 ID

how to get id of BorderContainer at runtime in Flex

我在运行时尝试获取 BorderContainer 的 ID 时遇到错误。我尝试使用 getStyle 但它也失败了。

    <s:Panel id="colorPanel" 
         title="Dem display color"
         width="500" height="500">
    <s:layout>
        <s:BasicLayout/>
    </s:layout>
    <s:Label id="label" y="4" horizontalCenter="0"/>
    <s:BorderContainer id="Box1" x="70" y="70" height="50" width="50" backgroundColor="#0000ff">

    </s:BorderContainer>
    <s:BorderContainer id="Box2" x="90" y="90" height="51" width="50" backgroundColor="#00ff00">

    </s:BorderContainer>
    <s:BorderContainer id="Box3" x="50" y="50" height="52" width="50" backgroundColor="#ff0000">

    </s:BorderContainer>

    <s:Button label="Click" click="
              colorPanel.setElementIndex(colorPanel.getElementAt(0),3);
              label.text = ""+colorPanel.getElementAt(0).id ;
              ">

    </s:Button>
</s:Panel>

我发现 Adob​​e 的解决方案似乎过于僵化。当我将返回的元素转换为 BorderContainer 时,我能够获得 Id 的值。所以我们必须忍受它,直到 Adob​​e 降低编译器对我们的期望。

label.text = ""+ BorderContainer(colorPanel.getElementAt(0)).id ;

不用转换为 BorderContainer,转换为 UIComponent 是安全的。在您的示例中,当返回的元素是 Label 而不是 BorderContainer 时,它会崩溃。您可以按以下方式进行:

<?xml version="1.0"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark">
<fx:Script><![CDATA[
    import mx.core.UIComponent;
    ]]></fx:Script>
<s:Panel id="colorPanel"
         title="Dem display color"
         width="500" height="500">
    <s:layout>
        <s:BasicLayout/>
    </s:layout>
    <s:Label id="label" text="Red" y="4" horizontalCenter="0"/>
    <s:BorderContainer id="Blue" x="70" y="70" height="50" width="50" backgroundColor="#0000ff">

    </s:BorderContainer>
    <s:BorderContainer id="Green" x="90" y="90" height="51" width="50" backgroundColor="#00ff00">

    </s:BorderContainer>
    <s:BorderContainer id="Red" x="50" y="50" height="52" width="50" backgroundColor="#ff0000">

    </s:BorderContainer>

    <s:Button label="Click" click="{
          colorPanel.setElementIndex(colorPanel.getElementAt(1),3);
          label.text = UIComponent(colorPanel.getElementAt(3)).id;}"/>
</s:Panel>
</s:Application>