How to reference XAML objects in code-behind of another page-Collection of common programming errors
App.xaml.cs cannot use the NavigationService directly because it is an application object, not a page object. However, it can invoke NavigationService through the RootFrame (i.e., the current page):
RootFrame.Navigate(new Uri(“/NextPage.xaml”, UriKind.Relative)); |
If you want to pass a string between App.xaml.cs and the page, you can define a public static string variable that can be accessed from both classes.
However, I have a feeling that the tutorial code example isn’t the best model for what you want to do.
The code example shows how to create global ApplicationBars in App.xaml that can be reused in different pages in your application. If you only need to use those appbars in one Pivot page, it would be easier to define them on locally that page instead of globally in App.xaml. Doing it this way would eliminate the issues you encountered. The article actually mentions it briefly: “For the purposes of this example, you create two global Application Bars by using XAML in App.xaml. In your applications, you can also create global Application Bars by using only code in the App.xaml code-behind file, or local Application Bars in the code-behind file of your pivot page“.
To put the ApplicationBars in your Pivot page instead of App.xaml, modify the example as follows:
- Instead of putting the ApplicationBars in in App.xaml, put them in in your Pivot page xaml:
- Put all the click handlers in your Pivot page code behind, instead of App.xaml.cs
- In the Pivot’s SelectionChanged handler, change it to access the local ApplicationBar, not global ones in App.xaml:
private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e) { switch (((Pivot)sender).SelectedIndex) { case 0: ApplicationBar = ((ApplicationBar)this.Resources[“AppBar1”]); break; case 1: ApplicationBar = ((ApplicationBar)this.Resources[“AppBar2”]); break; } }
Richard Woo