建立自定義初始螢幕視窗

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 IsIndeterminate="True" />
        <TextBlock HorizontalAlignment="Center"
                   VerticalAlignment="Center">Loading...</TextBlock>
    </Grid>
</Window>

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

public partial class App
{
    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(() =>
        {
            //simulate some work being done
            System.Threading.Thread.Sleep(3000);

            //since we're not on the UI thread
            //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" 屬性。