windows 8 App从App.xaml.cs访问页面方法

可能是一个愚蠢的问题所以我提前道歉。 我是构建Windows 8商店应用程序的新手。

当应用程序被挂起时,我需要在我的页面脚本上运行一些方法。 我只有一个页面,我在Page1.xaml.cs文件中有一些公共方法。 我想从App.xaml.cs文件中的OnSuspending()方法调用它们。 我需要确保保存一些文本文件。

如何创建对Page1脚本的引用?

您可以尝试从当前Frame Content属性访问Page1对象。 像这样的东西:

 var currentFrame = Window.Current.Content as Frame; var page1 = currentFrame.Content as Page1; 

然后可以从page1变量访问Page1公共方法:

 page1.SomePublicMethod(); 

如果从另一个线程触发代码,有时你必须运行它的主线程,这对我有用。

 Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { try { ProjectsPage projectsPage = (Window.Current.Content as AppShell).AppFrame.Content as ProjectsPage; projectsPage.FetchProjects(); } catch (Exception ex) { } }); 

这对我有用