使用按钮组件切换selectedIndex

时间:2011-04-19 21:37:44

标签: flex actionscript-3 mxml flash-builder

我试图在主应用程序上控制ViewStack的selectedIndex属性。我在main.mxml中分配了一个变量。我试图通过自定义组件中的函数来操作该变量; viewControl.mxml。我已经能够使用buttonBar模拟效果,但我宁愿用按钮来完成。

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" 
           xmlns:comps="comps.*" minWidth="955" minHeight="600">
<fx:Script>
    <![CDATA[
        import comps.viewControl;

        [Bindable]
        public var mainIndex:int = 0;


    ]]>
</fx:Script>

<comps:viewControl id="myControl"/>

<mx:ViewStack id="lgViewStack" selectedIndex="{mainIndex}">

    <s:NavigatorContent id="view1">
        <s:Panel id="firstPanel">
        </s:Panel>
    </s:NavigatorContent>
    <s:NavigatorContent id="view2">
        <s:Panel id="secondPanel">
        </s:Panel>
    </s:NavigatorContent>

</mx:ViewStack>

组件viewControl.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[

        protected function changeView(index:int):void
        {
            mainIndex = index;

        }
    ]]>
</fx:Script>

<s:Button id="myButton" click="changeView(1);"/>

编译时,我收到以下错误消息:在viewControl.mxml中访问未定义的属性mainIndex。我可以用函数集或函数来从Main.mxml中获取mainIndex吗?

1 个答案:

答案 0 :(得分:3)

正如您的评论中所提到的,变量范围就是问题所在。有很多方法可以满足您的需要,但实际上您需要一个可以在同一范围内引用视图堆栈和视图控件的地方(也就是来自另一个类)。创建整个框架只是为了提供一种在需要的地方获取这些引用的方法,但在您的情况下它恰好非常简单,因为父组件已经引用它们。

在视图组件中,创建一个本地(公共和可绑定)变量,以根据按钮单击存储当前索引...

<?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[

        [Bindable]
        public var selectedIndex:int;

        protected function changeView(index:int):void
        {
            this.selectedIndex = index;

        }
    ]]>
</fx:Script>

<s:Button id="myButton" click="changeView(1);"/>

然后在父组件中,您可以直接绑定到视图组件的selectedIndex ...

<comps:viewControl id="myControl"/>

<mx:ViewStack id="lgViewStack" selectedIndex="{myControl.selectedIndex}">
</mx:ViewStack>

另一种方法是在索引更改时在viewControl中调度一个事件。然后,您可以在父组件中使用事件处理程序执行类似的操作...

protected myControl_changeHandler(event:Event):void
{
  this.mainIndex = myControl.selectedIndex;
}

这样你就可以确保你的父组件也有索引的最新引用......