WPF does not support displaying anything other than an image as a splash screen out-of-the-box, so we'll need to create a Window
which will serve as a splash screen. We're assuming that we've already created a project containing MainWindow
class, which is to be the application main window.
First off we add a SplashScreenWindow
window to our project:
<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>
Then we override the Application.OnStartup
method to show the splash screen, do some work and finally show the main window (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();
});
});
}
}
Lastly we need to take care of the default mechanism which shows the MainWindow
on application startup. All we need to do is to remove the StartupUri="MainWindow.xaml"
attribute from the root Application
tag in App.xaml file.