Question

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();
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top