I am trying to control the selectedIndex property of a ViewStack on the main application. I have a variable assigned in main.mxml. I am attempting to manipulate that variable through a function in the custom component; viewControl.mxml. I have been able to simulate the effect with a buttonBar, but I would rather it be done with a button.
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>
And the component 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);"/>
When compiled, I receive the following error message: Access of undefined property mainIndex in viewControl.mxml. Is there something I can do with function set or function get to grab mainIndex from Main.mxml?
As mentioned in your comment, the variable scope is the issue. There are many ways to do what you need, but essentially you need a place where you can reference both your view stack and your view control in the same scope (aka from another class). There are entire frameworks created simply to provide a way to get these references where you need them, but it happens to be quite simple in your case since the parent component references them both already.
In your view component, create a local (public and bindable) variable to store the current index based on the button click…
Then in the parent component you can bind directly to the selectedIndex of the view component…
Another way to do this is to dispatch an event in your viewControl whenever the index changes. You can then do something like this in using an event handler in the parent component…
This way you can make sure your parent component has an up to date reference to the index as well…