使用進度報告建立啟動畫面視窗

WPF 不支援將影象以外的任何內容顯示為開箱即用的啟動畫面,因此我們需要建立一個 Window 作為啟動畫面。我們假設我們已經建立了一個包含 MainWindow 類的專案,該專案是應用程式主視窗。

首先,我們在專案中新增一個 SplashScreenWindow 視窗:

<Window x:Class="SplashScreenExample.SplashScreenWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        WindowStartupLocation="CenterScreen"
        WindowStyle="None"
        AllowsTransparency="True"
        Height="30"
        Width="200">
    <Grid>
        <ProgressBar x:Name="progressBar" />
        <TextBlock HorizontalAlignment="Center"
                   VerticalAlignment="Center">Loading...</TextBlock>
    </Grid>
</Window>

然後我們在 SplashScreenWindow 類上公開一個屬性,以便我們可以輕鬆更新當前進度值( SplashScreenWindow.xaml.cs ):

public partial class SplashScreenWindow : Window
{
    public SplashScreenWindow()
    {
        InitializeComponent();
    }

    public double Progress
    {
        get { return progressBar.Value; }
        set { progressBar.Value = value; }
    }
}

接下來我們覆蓋 Application.OnStartup 方法以顯示啟動畫面,做一些工作並最終顯示主視窗( App.xaml.cs ):

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        //initialize the splash screen and set it as the application main window
        var splashScreen = new SplashScreenWindow();
        this.MainWindow = splashScreen;
        splashScreen.Show();

        //in order to ensure the UI stays responsive, we need to
        //do the work on a different thread
        Task.Factory.StartNew(() =>
        {
            //we need to do the work in batches so that we can report progress
            for (int i = 1; i <= 100; i++)
            {
                //simulate a part of work being done
                System.Threading.Thread.Sleep(30);

                //because we're not on the UI thread, we need to use the Dispatcher
                //associated with the splash screen to update the progress bar
                splashScreen.Dispatcher.Invoke(() => splashScreen.Progress = i);
            }

            //once we're done we need to use the Dispatcher
            //to create and show the main window
            this.Dispatcher.Invoke(() =>
            {
                //initialize the main window, set it as the application main window
                //and close the splash screen
                var mainWindow = new MainWindow();
                this.MainWindow = mainWindow;
                mainWindow.Show();
                splashScreen.Close();
            });
        });
    }
}

最後,我們需要處理在應用程式啟動時顯示 MainWindow 的預設機制。我們需要做的就是從 App.xaml 檔案中的根 Application 標記中刪除 StartupUri="MainWindow.xaml" 屬性。