WPF project with zero reference exception

I have a WPF project, I use several WPF windows. My WPF windows:

  • Mainwindow
  • Window1
  • To come in

I have case scripts, in the first one everything works fine, but in the second I get an exception with a null reference.

  • First scenario: App.xaml is configured so that the launch window is MainWindow .

When the user clicks the Button on MainWindow button, he is sent to Window1 if I have the following code:

 MainWindow obj=(MainWindow)Application.Current.MainWindow; private void button1_Click(object sender, RoutedEventArgs e) { obj.checkBox1.IsChecked = false; } 

2. Second scenario: App.xaml is configured so that the launch window is the login window. Login Code:

 private void button1_Click(object sender, RoutedEventArgs e) { var window=new MainWindow(); window.Show(); this.Close(); } 

In this case, when I click the button in Window1, a null reference exception is thrown for obj.

What is the difference in initializing MainWindow in these two cases, which causes an exception in the second case, and how can I overcome it?

+4
source share
2 answers

So, the first Window that opens when the application starts will become the window that you will return when you call Application.Current.MainWindow .

In your case, this is Login , but in Window1 you expect it to be MainWindow , which is wrong. Since Login was closed, you will get null back and the application will work.

To fix this, you should do MainWindow MainWindow :-)

You can do it in Login like this:

 var window = new MainWindow(); Application.Current.MainWindow = window; window.Show(); this.Close(); 
+5
source

this.Close() in your script entry window 2 will close the application, since this window is indicated in your app.xaml file as the initial window. See property MainWindow

MainWindow is automatically installed with reference to the first Window object to be created in AppDomain.

In the first scenario, you do not close MainWindow for the application to continue. In the second, you close the login window for the application to exit.

In the first scenario, you do not show where the user is redirected to window1. It would also be helpful to see this code.

0
source

All Articles