[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();
}
參考資料:
文章標籤
全站熱搜
