同一 AppDomain 中的多个 WPF 应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28586582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple WPF applications in the same AppDomain
提问by JayTee
I got following setup:
我得到了以下设置:
WPF_Application.exe
WPF_Application.exe
and
和
a DLL that contains a WinForms Window and an WPF Window.
一个包含 WinForms 窗口和 WPF 窗口的 DLL。
The 'WPF_Application.exe' calls the WinForms window from the DLL and the WinForms Window creates an instance of the WPF window in the DLL.
“WPF_Application.exe”从 DLL 调用 WinForms 窗口,WinForms 窗口在 DLL 中创建 WPF 窗口的实例。
That creates following exception:
这会产生以下异常:
Cannot create more than one System.Windows.Application instance in the same AppDomain.
不能在同一个 AppDomain 中创建多个 System.Windows.Application 实例。
Tried different things, but couldn't figure out how to fix it.
尝试了不同的东西,但无法弄清楚如何解决它。
回答by JayTee
I fixed it by asigning the Application of the wpf window that is called to the Application.Current Window:
我通过将被调用的 wpf 窗口的应用程序分配给 Application.Current 窗口来修复它:
if (Application.Current == null)
{
MyApplication = new Application
{
ShutdownMode = ShutdownMode.OnExplicitShutdown
};
}
else
MyApplication = Application.Current;
回答by Nicolas Repiquet
System.Windows.Application is a singleton: its constructor must only be invoked once (including App.xaml de-xamlization), or exception is thrown.
System.Windows.Application 是一个单例:它的构造函数只能被调用一次(包括 App.xaml de-xamlization),否则会抛出异常。
I'm affraid there is not much you can do about it, except maybe check if Application.Current is set before starting your second application, and somewhat use that instance to load it.
我很害怕你对此无能为力,除非在启动第二个应用程序之前检查 Application.Current 是否已设置,并在某种程度上使用该实例来加载它。
Or you can create another AppDomain, and use it to launch the second application.
或者您可以创建另一个 AppDomain,并使用它来启动第二个应用程序。
回答by Aaron Thompson
Make sure you only have one Application defined in XAML.
确保您只在 XAML 中定义了一个应用程序。
Visual studio creates an App.xamlwhen making a new WPF solution, if you have created a new .xaml file with the <Application></Application>tag, this will cause this error and the solution will build but fail at runtime.
Visual Studio 在创建App.xaml新的 WPF 解决方案时会创建一个,如果您创建了一个带有<Application></Application>标记的新 .xaml 文件,这将导致此错误并且该解决方案将构建但在运行时失败。
Delete the duplicate application and use Windowor UserControlto have multiple windows.
删除重复的应用程序并使用Window或UserControl拥有多个窗口。

