Application.Current in ElementHost is null
Asked Answered
T

1

18

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?

Tithing answered 30/8, 2012 at 13:41 Comment(1)
When i call the new System.Windows.Application(); second time from my windows form, am getting the error message "Cannot create more than one System.Windows.Application instance in the same AppDomain." Actually from my windows application when i close the form System.Windows.Application.Current" object becomes null, and when i open the form again from main window, it tries to create new object of Application() and it fails from second time onwards. Any solution or workaround please...Matelda
S
41

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();
} 
Strader answered 7/2, 2013 at 14:50 Comment(6)
oooh. Yay! Thank you. This is just what I was after :DAnteater
Very useful information - I am coding add-ins for ArcGIS and when creating a WPF add-in this is necessary to use Application.Current within the WPF code.Crownwork
You should not create second Application Context, than you will have two applications running at the same time, that means also you will have two UI dispatchers. You can loose control of your application then.Marquess
When i call the new System.Windows.Application(); second time from my windows form, am getting the error message "Cannot create more than one System.Windows.Application instance in the same AppDomain."Matelda
did you verify for (null == System.Windows.Application.Current) ?Strader
does not help??Abrogate

© 2022 - 2024 — McMap. All rights reserved.