如何在 WPF 中的 MainWindow 之前像启动画面一样打开子窗口?

use*_*149 1 wpf

我有两个xaml。一个是 MainWindow,另一个是 NewWindow。我想在程序运行时显示 NewWindow 5 秒。5 秒后,我想显示 MainWindow。

如何在 WPF 中更改 xaml?

这是主窗口。

<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>
Run Code Online (Sandbox Code Playgroud)

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是新窗口。

<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>
Run Code Online (Sandbox Code Playgroud)

public partial class NewWindow : Window
{
    public NewWindow()
    {
        InitializeComponent();
    }
}
Run Code Online (Sandbox Code Playgroud)

She*_*dan 5

1) 首先,我们需要在MainWindow运行应用程序后立即停止打开。为此,首先StartupUri="MainWindow.xaml"App.xaml文件中删除设置并通过设置Startup属性来替换它:

<Application x:Class="AppName.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Startup="App_Startup">
Run Code Online (Sandbox Code Playgroud)

2)然后,为Application.Startup事件添加处理程序并启动您的孩子(或启动画面)Window

private SplashScreen splashScreen;
Run Code Online (Sandbox Code Playgroud)

...

public void App_Startup(object sender, StartupEventArgs e)
{
    // Open your child Window here
    splashScreen = new SplashScreen();
    splashScreen.Show();
}
Run Code Online (Sandbox Code Playgroud)

3)此时,有几种不同的方法可以走,取决于您是否需要等待SplashScreen Window执行任何操作。在这个特定问题中,要求是MainWindow在 5 秒后简单地打开,所以我们需要一个DispatcherTimer

public void App_Startup(object sender, StartupEventArgs e)
{
    // Open your child Window here
    splashScreen = new SplashScreen();
    splashScreen.Show();
    // Initialise timer
    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = new TimeSpan(0, 5, 0);
    timer.Tick += Timer_Tick;
}
Run Code Online (Sandbox Code Playgroud)

...

private void Timer_Tick(object sender, EventArgs e)
{
    splashScreen.Close();
    MainWindow mainWindow = new MainWindow();
    mainWindow.Show();
}
Run Code Online (Sandbox Code Playgroud)

就是这样。