Frage

I have two WPF applications (say App1 and App2) that run fine separately. I decided that I wanted to be able to instantiate and open App2's main window from App1, so that I can use App1 as a start screen for both apps. I did this by adding a reference to App2 in the App1 project in Visual Studio and adding its namespace in a Using statement. For the most part this works fine, except for one thing.

Both applications contain a public variable called Storeid that is declared in App.xaml.cs. The code that I use to access it is the following:

        Application TheApp = App.Current;
        App MyApp = TheApp as App;
        _storeid = MyApp.Storeid;

This code is called from App2's main window's constructor.

This code works fine when App2 is run independently. However, it fails when the same window is instantiated from App1. The first line works fine, but when it gets to the second line, the cast returns Null, and thus the 3rd line fails due to a null reference exception.

Now, I realize that App.Current would be different in the two cases. I would expect it to use App.Current (and the definition of App) from App2 when it's run independently, and for it to use App.Current and App from App1 when instantiated from App1. Both of the App.xaml.cs have the Storeid public variable, so I would expect the code to work fine. I just don't understand why when I cast TheApp to App in the second line, the cast produces a null value.

War es hilfreich?

Lösung

Probably because even though they have the same name, Type App in App2 is different from Type App in App1. Since the application that is running is App2, you're trying to cast an instance of App1's App Type to App2's App Type. The result is null.

That is, App2 is trying to cast App.Current to App2's App Type. But the property's type is App1's App Type. I hope that's clear.

You're going to have to determine in App2's copy of the code you posted which App type is the type of App.Current & dereference the store ID using different logic if it's App1's App Type than if it's App2's App Type.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top