Silverlight Tip of the Day #72 - How to call Page.xaml.cs from App.xaml.cs
Your App class (App.xaml + App.xaml.cs) is primarily used for global events and declarations such as styles.
The primary events this class handles by default include:
- Application_Startup() - called when the applications starts.
- Application_Exit() - called when the application is exiting.
- Application_UnhandledException() - called when an unhandled exception has occurred.
Your Page class (Page.xaml + Page.xaml.cs) is where you will typically put the core application logic and UI declarations. Now, what if you want to communicate with your game logic in your Page class when an event such as Application_Exit() is fired in App class?
In Application_Startup() our App class creates an instance of your page class and stores it as a UIElement under the property RootVisual:
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new Page();
}
To illustrate the call let's add a public getter function in Page.xaml.cs:
public partial class Page : UserControl
{
private static bool _done = false;
public bool Done
{
get { return _done; }
set { _done = value; }
}
}
In order to call any public members in the page class you will have to typecast RootVisual to be a Page since by default it is a UIElement. In App.xaml.cs let's make a call to set done = true in the Page class when the application has exited:
private void Application_Exit(object sender, EventArgs e)
{
((Page)this.RootVisual).Done = true;
}
Thank you,
--Mike Snow
Subscribe in a reader