我有一个具有第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页中调用了ResumingMethod,因此Camera初始化了,这不是我要的。
有什么方法可以只为页面添加一个暂停事件处理程序吗?
您可以在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();
}
这样比较好,因为当页面不可见时,您将取消订阅Suspending / Resuming事件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句