Alternative for ViewStack.selectedIndex
Posted by admin on October 31st, 2008
ViewStacks are great for storing containers and showing the one that is needed.
You can use the view stacks selectedIndex property for changing between the different views. However, by using the selectedIndex, often you have to change the indexes, because in case you comment or remove a container the indexes are changing for the views that are remaining.
The view stack has a selectedChild property, where you can set the view that needs to be shown by his id, but for using that in any part of the application, you should have access to the container.
Instead of using the id, I came up with a solution by using the containers name. Here it is:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*" > <mx:Script> <![CDATA[ import mx.core.Container; import mx.core.UIComponent; [Bindable] public static var STACK_CONTENT_NAME_1:String = 'stack1'; [Bindable] public static var STACK_CONTENT_NAME_2:String = 'stack2'; [Bindable] public static var STACK_CONTENT_NAME_3:String = 'stack3'; [Bindable] public static var STACK_CONTENT_NAME_4:String = 'stack4'; private function onClick():void{ myViewStack.selectedChild = myViewStack.getChildByName(STACK_CONTENT_NAME_3) as Container; } ]]> </mx:Script> <mx:VBox> <mx:LinkBar dataProvider="{myViewStack}" /> <mx:ViewStack id="myViewStack"> <mx:HBox label="ViewStack Item #1" name="{STACK_CONTENT_NAME_1}"> <mx:Label text="ViewStack Content #1" /> </mx:HBox> <mx:HBox label="ViewStack Item #2" name="{STACK_CONTENT_NAME_2}"> <mx:Label text="ViewStack Content #2" /> </mx:HBox> <mx:HBox label="ViewStack Item #3" name="{STACK_CONTENT_NAME_3}"> <mx:Label text="ViewStack Content #3" /> </mx:HBox> <mx:HBox label="ViewStack Item #4" name="{STACK_CONTENT_NAME_4}"> <mx:Label text="ViewStack Content #4" /> </mx:HBox> </mx:ViewStack> <mx:Button label="change" click="onClick()" /> </mx:VBox> </mx:Application>