ElementHost中的Application.Current为null

Dav*_*vid 16 windows user-controls elementhost winforms

我在我的个人Libs中使用WPF UserControl.Libs包含在我的WPF和WindowsForms程序中.现在我的UserControl必须显示一个新的(WPF)窗口.在新窗口我想设置所有者.我是这样做的:

dialog.Owner = Application.Current.MainWindow;
Run Code Online (Sandbox Code Playgroud)

如果我在WPF程序中使用UserControl,这可以正常工作.

当我在我的WindowsForms程序中使用UserControl时(我在ElementHost中设置UserControl elementHost.Child = ...)为Application.Currentnull.

这不好,我的程序抛出异常.

为什么是Application.Currentnull?

Yur*_*riy 36

Application.Current特定于WPF应用程序.
因此,当您在WinForms应用程序中使用WPF控件时,您需要初始化WPF应用程序的实例.在您的WinForms应用程序中执行此操作.

if ( null == System.Windows.Application.Current )
{
   new System.Windows.Application();
} 
Run Code Online (Sandbox Code Playgroud)