[UWP] 在進入背景或進入前景時,觸發OnNavigatedTo, OnNavigatedFrom。

  每個Page都會有自己的進入頁面跟離開頁面的邏輯,有時會希望App進入背景 or 進入前景時也能夠呼叫到目前頁面的 OnNavigatedTo, OnNavigatedFrom,但預設是不會被呼叫的,

 

解法: 

在App.xaml.cs裡:

        public App()
        {
            this.InitializeComponent();

            this.Resuming += App_Resuming;
            this.Suspending += OnSuspending;
            this.LeavingBackground += App_LeavingBackground;
            this.EnteredBackground += App_EnteredBackground;
        }

        private void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e)
        {
            if (state == null)
            {
                return;
            }

            var frame = Window.Current.Content as Frame;
            frame.SetNavigationState(state);
        }

        private void App_EnteredBackground(object sender, EnteredBackgroundEventArgs e)
        {
            // 呼叫Page本身的OnNavigatedFrom
            var frame = Window.Current.Content as Frame;
            state = frame.GetNavigationState();
        }

參考資料: 

https://stackoverflow.com/questions/27055521/onnavigatedfrom-is-not-called-when-the-app-is-suspended/27056824#27056824

全站熱搜

小賢 發表在 痞客邦 留言(0) 人氣()