创建自定义初始屏幕窗口

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" 属性。