I have two xaml. One is MainWindow and other is NewWindow. I want show NewWindow 5 seconds, when program is run. And after 5 seconds, I want show MainWindow.
How to change xaml in WPF?
Here is MainWindow.
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
</Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
Here is NewWindow.
<Window x:Class="WpfApplication2.NewWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="NewWindow" Height="300" Width="300">
<Grid>
</Grid>
public partial class NewWindow : Window
{
public NewWindow()
{
InitializeComponent();
}
}
1) First, we need to stop
MainWindow
from opening as soon as we run the Application. To do this, first remove theStartupUri="MainWindow.xaml"
setting from theApp.xaml
file and replace it by setting theStartup
property instead:2) Then, add the handler for the
Application.Startup
event and launch your child (or splash screen)Window
:...
3) At this point, there are several different ways to go, dependent on whether you need to wait for the
SplashScreen Window
to do anything or not. In this particular question, the requirement is to simply open theMainWindow
after 5 seconds, so we'll need aDispatcherTimer
:...
That's it.
There are plenty ways to do this. As some people suggested i suggest too to DO NOT DO THIS if you're trying to create a splash screen, there are better ways to do that. But.. here what you asked for:
it's a simple background worker that waits for 5 seconds, then opens the NewWindow and close MainWindow. Yes, you can do it without background worker too, but
Thread.Sleep(5000);
will totally freeze your GUI and make your little app unresponsive, so you need another thread to wait while the main thread can keep your GUI alive. I suggest you to study at least how a background worker works.HERE the official MSDN documentation, but google is your friend and you can find tons of tutorial and explanation about it
The mainWindow should also be loaded before closing the splashScreen This way your splashscreen shows as long as it is loading.You can add additional time in the
splashScreen.Close()
Function.Here is another way to do it:
Set Startup to "App_Startup" as shown in one of the other posts.
And in App_OnStartup: