【问题标题】:DataTemplate not appeared in Application_StartupDataTemplate 未出现在 Application_Startup 中
【发布时间】:2016-04-05 06:44:37
【问题描述】:

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

已正确注册 ViewModel 和 ResourceDictionary。

App.xaml

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


应用程序.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();
    }
}

【问题讨论】:

  • DataTemplate 将在绑定时工作,这发生在 InitializeComponent 方法之后。因此,请将您的 SplashWorker 代码放入应用程序的 Startup 事件中。
  • 我添加了一个正式的答案,并为形式提供了适当的信用

标签: c# wpf xaml datatemplate splash-screen


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多