basquang™ on clouds

September 26, 2013

Windows Store RT: Access controls in other page

Filed under: Windows Store 8 — basquang @ 3:20 PM
Tags: ,

When develop Windows Store App, sometime you may want to access controls in another page. For example: In the MainPage, you are playing background music using MediaElment control. Your app has SettingsFlyout page to allow user enable/disable the background music via ToggleSwitch control. You want Application must stop/start music right from user switch toggleswitch control in SettingsFlyout page. The question is how to implement that case? You cannot override the event OnNavigatedFrom/OnNavigatedTo in both page, because they are not navigate anymore.

The solution is use “Window.Current.Content” to detect current page, then navigate to the control in that page. See example code bellow:

 

 public sealed partial class SettingsFlyoutPage : SettingsFlyout
    {
        public SettingsFlyoutPage()
        {
            this.InitializeComponent();
            toggleSwitchMusic.Toggled += toggleSwitchMusic_Toggled;
        }

        void toggleSwitchMusic_Toggled(object sender, RoutedEventArgs e)
        {
            
            Frame rootFrame = Window.Current.Content as Frame;
            //Detect the page need to access its control
            if (rootFrame.Content.GetType().Equals(typeof(MainPage)))
            {
                MainPage mainPage = rootFrame.Content as MainPage;
                MediaElement backgroundMusic = mainPage.Content as MediaElement;
                backgroundMusic.IsMuted = !toggleSwitchMusic.IsOn;
                //mainPage.mediaElement.IsMuted = !toggleSwitchMusic.IsOn;
            }
        }              
    }

Hope this help!

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: