问题
I think this is a bug in the WPF framework, without going into depths of my program and why I am doing what I am doing, I wrote a simple test application to prove my theory.
Can this issue be confirmed? What are possible workarounds for a series of dialogs to be executed before putting the application into its run loop?
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
namespace ShowDialogWindow
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
Window testWindow = new Window();
testWindow.ShowDialog();
testWindow.Close();
// THE CODE BELOW WILL NOT SHOW THE NEXT WINDOW
Window testWindow2 = new Window();
testWindow2.ShowDialog();
testWindow2.Close();
}
}
}
Update:
Sure I can change my design to accommodate this behaviour. What I was trying to do was really simple however.
I have derived my MyApplication
from Application
. On the Main()
, I initiate a series of start checks, for example, license information, splash screen, connectivity and configuration checks, ect. When I get my all clear, I call MyApplicatiom.Run(MyMainForm)
.
This design is based on a normal Windows application which works without a problem.
Thanks a lot for your help, and I will remember that you cannot call ShowDialog()
before application.Run()
as it simply innitializes a shutdown. I would have thought however that a shutdown sequence should only be initiated after a App.Run()
instruction.
Please correct me if I am understanding this wrong.
回答1:
Not a bug. The default ShutdownMode
of Application
is OnLastWindowClosed
, so as soon as the first window is closed your application will start shutting down! Change to OnExplicitShutdown
and it will work, but you'll have to manage the shutdown.
I think you probably just need to rethink what you're actually trying to achieve. Why would you display two subsequent dialog windows during the startup of your app?
回答2:
For anyone that has the same problem, here is how you can get around it:
public App()
{
// Preserve and temporarily switch shutdown mode
var oldShutdownMode = ShutdownMode;
ShutdownMode = ShutdownMode.OnExplicitShutdown;
var dialog = new Window();
var result = dialog.ShowDialog();
dialog = new Window();
result = dialog.ShowDialog(); // This will show!
// Reset shutdown mode to original value
ShutdownMode = oldShutdownMode;
}
来源:https://stackoverflow.com/questions/1243833/wpf-showdialog-returns-null-immediately-on-second-call