Windows Store RT: Access controls in other page

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!

Leave a Reply