我有一个包含第 1 页和第 2 页的应用程序,第 2 页仅使用 NavigationCacheMode.Required
实例化一次。
在第 2 页中,我正在使用相机,因此每次导航到应用程序的其他页面或暂停应用程序时,我都需要放置相机并稍后重新打开。
出于这个原因,我正在使用:
Application.Current.Resuming += ResumingMethod;
private async void ResumingMethod(Object sender, Object e)
{
Debug.WriteLine("RESUMING METHOD");
// instantiated the Camera
await this.Initialize();
}
第 1 页和第 2 页之间的导航工作正常,我可以从第 2 页暂停应用程序并毫无问题地恢复它。但是当我从第 2 页导航到第 1 页,暂停应用程序并恢复它时,在第 1 页中调用了恢复方法,因此相机已初始化,这不是我的内容。
有没有办法只为页面添加挂起事件处理程序?
你可以在 Page2 类中做这样的事情:
public Page2()
{
this.InitializeComponent();
Application.Current.Resuming += Application_Resuming;
}
void Application_Resuming(object sender, object e)
{
if (Frame.Content == this)
createCamera();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// This will be executed when you navigate to this page
// but not when resuming the app from the suspended state
// (unlike on Windows 8.1).
createCamera();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
// This will be executed when you navigate away from this page
// as well as if the application is suspended.
disposeCamera();
}
另一种方式:
public Page2()
{
this.InitializeComponent();
this.Loaded += Page2_Loaded;
this.Unloaded += Page2_Unloaded;
}
void Page2_Loaded(object sender, EventArgs e)
{
Application.Current.Suspending += Application_Suspending;
Application.Current.Resuming += Application_Resuming;
createCamera();
}
void Page2_Unloaded(object sender, EventArgs e)
{
Application.Current.Suspending -= Application_Suspending;
Application.Current.Resuming -= Application_Resuming;
disposeCamera();
}
void Application_Suspending(object sender, SuspendingEventArgs e)
{
disposeCamera();
}
void Application_Resuming(object sender, object e)
{
createCamera();
}
这种方式更好,因为当页面不可见时,您将取消订阅挂起/恢复事件。
恢复/暂停特定于页面,我认为您可以使用Page.Loaded和Page.Unloaded事件:
public BasicPage1()
{
this.InitializeComponent();
this.Loaded += (s, e) =>
{
Application.Current.Resuming += ResumingMethod;
};
this.Unloaded += (s, e) =>
{
Application.Current.Resuming -= ResumingMethod;
};
}