I have an unmanaged application which uses a WPF assembly for some of its user interface. Because of this arrangement Application.Current
is not created automatically. So when the first WPF window is loaded, my code does this:
if (System.Windows.Application.Current == null)
{
new System.Windows.Application();
}
This works the first time and is the approach I've seen recommended.
But if the user closes the (only) WPF window, and later loads it again, even though Current == null
again an exception is thrown when the Application ctor is called.
It is clear in the documentation that you can only have one Application per AppDomain - but why then is Current null and yet I can't create it?
The exception that is thrown is of type InvalidOperationException
and has the message:
Cannot create more than one System.Windows.Application instance in the same AppDomain.
Its InnerException
is null.
To work around this I have tried to:
Construct
Application
usingShutdownMode = ShutdownMode.OnLastWindowClose
Explicitly call
Current.Shutdown()
when the WPF window is closed
but neither has made any difference.
Is there some other way to manually manage the lifetime of the Current
object? Or should I instead attempt to create it when the unmanaged application starts, and then rely on it always being set for the lifetime of the process?