本文介绍了WPF 在主窗口之前显示对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在主窗口之前显示对话窗口(例如登录/选项等)?

How one can show dialog window (e.g. login / options etc.) before the main window?

这是我尝试过的(显然 有曾经工作过,但现在不行了):

Here is what I tried (it apparently has once worked, but not anymore):

XAML:

<Application ...
    Startup="Application_Startup">

应用程序:

public partial class App : Application
{
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        Window1 myMainWindow = new Window1();
        DialogWindow myDialogWindow = new DialogWindow();
        myDialogWindow.ShowDialog();
    }
}

结果:首先显示 myDialogWindow.当它关闭时,Window1 会按预期显示.但是当我关闭 Window1 时,应用程序根本没有关闭.

Outcome: myDialogWindow is shown first. When it is closed, the Window1 is shown as expected. But as I close Window1 the application does not close at all.

推荐答案

这是对我有用的完整解决方案:

Here's the full solution that worked for me:

App.xaml 中,我删除了 StartupUri 内容,并添加了一个 Startup 处理程序:

In App.xaml, I remove the StartupUri stuff, and add a Startup handler:

<Application x:Class="MyNamespace.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="ApplicationStart">
</Application>

App.xaml.cs 中,我将处理程序定义如下:

In App.xaml.cs, I define the handler as follows:

public partial class App
{
    private void ApplicationStart(object sender, StartupEventArgs e)
    {
        //Disable shutdown when the dialog closes
        Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

        var dialog = new DialogWindow();

        if (dialog.ShowDialog() == true)
        {
            var mainWindow = new MainWindow(dialog.Data);
            //Re-enable normal shutdown mode.
            Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
            Current.MainWindow = mainWindow;
            mainWindow.Show();
        }
        else
        {
            MessageBox.Show("Unable to load data.", "Error", MessageBoxButton.OK);
            Current.Shutdown(-1);
        }
    }
}

这篇关于WPF 在主窗口之前显示对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:12