user3524628
user3524628

Reputation: 137

Current Window Content cannot be identified anymore

I have programmed code on top of the MainWindow content. As I added a login-mask to start before the MainWindow my programmed content distribution does not work properly anymore.

The code when the MainWindow is called and the login-mask is closed:

Login-Mask Window Code (after successful login)

MainWindow popup = new MainWindow();
popup.Show();
this.Close();

Within the MainWindow I am calling my content like this which still works when the MainWindow was called:

MainWindow Content Code

this.contentControl.Content = new UserControlXYZ();

Now when I call another UserControl from the new loaded contentControl.Content I get a NullPointerException (Before adding the login-mask it was loaded):

UserControlXYZ Content Code

 (Application.Current.MainWindow.FindName("contentControl") as ContentControl).Content = new UserControlNEWControl();

Upvotes: 1

Views: 69

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81283

Appication main window gets set to the window which is the start up window for an application. So, in your case it will be Login window and since you have closed it, Application.Current.MainWindow will return null.

In case you want to get MainWindow, you can get it from Windows collection like this:

MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().First();
mainWindow.contentControl.Content = new UserControlNEWControl();

To use OfType<T>() and First() extension methods, add System.Linq namespace in your class.

Upvotes: 2

Related Questions