我的应用程序在启动过程中遇到问题。我遇到异常,上面写着
A method was called at an unexpected time. Could not create a new view because the main window has not yet been created
首先,我显示一个启动屏幕,以便我可以在后台从互联网获取一些数据。我的启动屏幕工作正常,并且我按照文档中的指示正确实现了它。
在 App.xaml.ca 中,我有一些用于启动屏幕的标准代码
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
...
if (e.PreviousExecutionState != ApplicationExecutionState.Running)
{
bool loadState = (e.PreviousExecutionState == ApplicationExecutionState.Terminated);
ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen, loadState);
Window.Current.Content = extendedSplash;
}
...
Window.Current.Activate();
}
然后在我的应用程序构造函数中我有这个
public static Notifications notifications;
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
SomeClass.RunTasks(); //acquire data from a REST service
//initializing the object for subscribing to push notification, not sure if this is the best place to put this.
App.notifications = new Notifications("hubname", "myEndpoint");
}
异常发生在我的 RunTasks() 方法中,如下所示
public class SomeClass
{
GetHTTPResponse _aggregateData = new GetHTTPResponse("http://someRestService");
public async void RunTasks()
{
try
{
HttpResponseMessage aggregateData = await _aggregateData.AcquireResponse();
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
//do a bunch of stuff with the data
//NOTE: I am making updates to my ViewModel here with the data I acquired
//for example App.ViewModel.Time = somevalue
//when finished dismiss the splash screen
ExtendedSplash.Instance.DismissExtendedSplash();
}
);
}
catch (System.Exception ex)
{
}
}
}
有什么想法可以改进这个并消除错误吗? 它是否与我更新 ViewModel 项(这些项是绑定(bind)到 UI 组件的数据)有关?
编辑当我从 App.cs 构造函数中删除通知对象的创建(并将其移动到 RunTasks() 方法中时,错误就会消失。
App.notifications = new Notifications("hubname", "myEndpoint");
最佳答案
出现异常的原因是 Windows.ApplicationModel.Core.CoreApplication.MainView 在应用程序的构造函数中无效,因为尚未创建主视图。
收到 Application.OnLaunched/OnActivated 事件后即可访问它。
谢谢!
斯特凡·威克 - Windows开发者平台
关于c# - 无法创建新 View ,因为尚未创建主窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42822921/