无法创建新视图,因为尚未创建主窗口

时间:2017-03-15 23:55:51

标签: c# uwp splash-screen lifecycle

我在启动时遇到了应用程序问题。我得到的异常是

  

在意外时间调用了一个方法。无法创建   新视图,因为尚未创建主窗口

首先我显示一个启动画面,这样我就可以在后台从互联网上获取一些数据。我的启动画面工作正常,我按照文档中的说明正确实现了它。

在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();
}

然后在我的App构造函数中,我有了这个

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项目(绑定到UI组件的数据)有关吗?

编辑当我从App.cs构造函数中删除我的通知对象的创建(并将其移动到RunTasks()方法时,错误就消失了。

 App.notifications = new Notifications("hubname", "myEndpoint");

1 个答案:

答案 0 :(得分:0)

您获得异常的原因是因为Windows.ApplicationModel.Core.CoreApplication.MainView在您的应用程序的构造函数中无效,因为尚未创建主视图。

收到Application.OnLaunched / OnActivated事件后,您可以访问它。

谢谢!

Stefan Wick - Windows开发人员平台