我的WPF程序没有显示GUI元素

时间:2016-11-07 21:29:03

标签: c# wpf mahapps.metro

我有一个加载屏幕,从我的程序中显示,以防止我的程序在加载时看起来没有响应,但是当我使用loadingScreen.Show();this.Hide();时,加载屏幕窗口显示正常,但是没有出现MahApps.Metro的GUI元素,标签也没有。

这是我到目前为止的代码:

LoadingScreen screen = new LoadingScreen();
screen.InitializeComponent();
this.Hide();
screen.Show();

然后需要加载的东西,最后

screen.Hide();
this.Show();

1 个答案:

答案 0 :(得分:0)

我认为你有一个线程问题。您的启动画面锁定主线程,它永远不会到达您的主应用程序。这是我如何解决这个问题。我为启动画面和初始化创建了一个新线程。初始化完成后,我使用ManualResetEvent向主线程发出信号,主应用程序可以继续。

public partial class App : Application
{
    private static LoadingScreen splashScreen;
    private static ManualResetEvent resetSplash;

    [STAThread]
    private static void Main(string[] args)
    {
        try
        {
            resetSplash = new ManualResetEvent(false);
            var splashThread = new Thread(ShowSplash);
            splashThread.SetApartmentState(ApartmentState.STA);
            splashThread.IsBackground = true;
            splashThread.Name = "My Splash Screen";
            splashThread.Start();
            resetSplash.WaitOne(); //wait here until init is complete

            //Now your initialization is complete so go ahead and show your main screen
            var app = new App();
            app.InitializeComponent();
            app.Run();
        }
        catch (Exception ex)
        {
            //Log it or something else
            throw;
        }
    }

    private static void ShowSplash()
    {
        splashScreen = new LoadingScreen(); 
        splashScreen.Show();
        try
        {
            //this would be your async init code inside the task
            Task.Run(async () => await Initialization()) 
            .ContinueWith(t =>
                {
                    //log it
                }, TaskContinuationOptions.OnlyOnFaulted);
    }
    catch (AggregateException ex)
    {
        //log it
    }
    resetSplash.Set();
    Dispatcher.Run();
}

}