Application.Current in ElementHost is null

David picture David · Aug 30, 2012 · Viewed 8.4k times · Source

I use a WPF UserControl in my personal Libs. The Libs are included in my WPF and WindowsForms programs. Now my UserControl has to show a new (WPF) Window. At the new Window I want to set the Owner. I do it like this:

dialog.Owner = Application.Current.MainWindow;

This works fine, if i use the UserControl in a WPF program.

When I use the UserControl in my WindowsForms program (I set the UserControl in a ElementHost elementHost.Child = ...) is Application.Current null.

This is not good and my program throws an exception.

Why is Application.Current null?

Answer

Yuriy picture Yuriy · Feb 7, 2013

Application.Current is Specific for WPF Application.
Therefore when you are using WPF controls in WinForms Application you need to initialize instance of WPF Application. Do this in your WinForms Application.

if ( null == System.Windows.Application.Current )
{
   new System.Windows.Application();
}