DataTemplate未出现在Application_Startup中

时间:2016-04-05 06:44:38

标签: c# wpf xaml datatemplate splash

我正在App.c中制作启动画面。当我使用SplashWorker.RunWorkerAsync(); DataTemplate时没有出现。
但是在注释这段代码时,DataTemplate出现了......

已正确注册ViewModel和ResourceDictionary。

的App.xaml

<Application ..........   Startup="Application_Startup">


App.cs

private void Application_Startup(object sender, StartupEventArgs e)
{
    this.ShutdownMode = ShutdownMode.OnExplicitShutdown;

    SplashWindow sw = new SplashWindow();

    sw.Closed += (ss, ee) =>
    {
        if (ServiceLocator.Current.GetInstance<SplashViewModel>().ClosedByUser)
        {
            this.Shutdown();
        }
        ServiceLocator.Current.GetInstance<SplashViewModel>().Cleanup();
        sw = null;
    };

    if ((bool)sw.ShowDialog())
    {
        this.ShutdownMode = ShutdownMode.OnMainWindowClose;
        MainWindow = new MainWindow();
        MainWindow.Show();
    }
}

SplashViewModel.cs

 public SplashViewModel()
 {
     SplashWorker = new BackgroundWorker();
     SplashWorker.WorkerSupportsCancellation = true;
     SplashWorker.DoWork += SplashWorker_DoWork;
     SplashWorker.RunWorkerCompleted += SplashWorker_RunWorkerCompleted;
     Result = null;
     SplashWorker.RunWorkerAsync();
 }


private void Application_Startup(object sender, StartupEventArgs e)
{
    this.ShutdownMode = ShutdownMode.OnExplicitShutdown;

    SplashWindow sw = new SplashWindow();
    sw.Closed += (ss, ee) =>
    {
        if (ServiceLocator.Current.GetInstance<SplashViewModel>().ClosedByUser)
        {
            this.Shutdown();
        }
        ServiceLocator.Current.GetInstance<SplashViewModel>().Cleanup();
        sw = null;
    };

    sw.Loaded += (ss, ee) =>
    {
        ServiceLocator.Current.GetInstance<SplashViewModel>().RunWorker();
    };

    if ((bool)sw.ShowDialog())
    {
        this.ShutdownMode = ShutdownMode.OnMainWindowClose;
        MainWindow = new MainWindow();
        MainWindow.Show();
    }
}

1 个答案:

答案 0 :(得分:1)

正如@AnjumSKhan在评论中所提到的,将SplashWorker代码移到应用程序的Startup事件中,因为DataTemplate在绑定时会起作用,这在InitializeComponent方法之后发生。