stuicidle
stuicidle

Reputation: 317

C# what is causing this odd behaviour when accessing Static property in WPF main window from App.xaml.cs

I have the public static property "inDevMode" in the Main Window of my WPF project, I am setting this property based on command line params when starting the application.

MainWindow mainWindow = new MainWindow();
if (startInDevMode)
{
    MainWindow.inDevMode = true;
}
mainWindow.Show();

The "MainWindow" within the curly braces is not highlighted grey (which the other two type references are) and when compiling I get this message:

'Window' does not contain a definition for 'inDevMode' and no extension method 'inDevMode' accepting a first argument of type 'Window' could be found (are you missing a using directive or an assembly reference?)

If I change what is within the braces to an instance reference (as below), which I know is wrong when accessing a static property:

MainWindow mainWindow = new MainWindow();
if (startInDevMode)
{
    mainWindow.inDevMode = true;
}
mainWindow.Show();

I get this error:

Member 'MainWindow.inDevMode' cannot be accessed with an instance reference; qualify it with a type name instead

But if I change the identifier of the "mainWindow" instance to "MainWindow" as below then I get no errors?

MainWindow MainWindow = new MainWindow();
if (startInDevMode)
{
    MainWindow.inDevMode = true;
}
MainWindow.Show();

and the type reference within the curly braces ("MainWindow") is now grey

Upvotes: 2

Views: 69

Answers (1)

mm8
mm8

Reputation: 169320

MainWindow is a property of the Application class that returns a Window and this type has no "inDevMode" property. That's why you get the error. You have a naming conflict.

You could qualify the name of the MainWindow type with the namespace in order to be able to set the static property:

MainWindow mainWindow = new MainWindow();
if (startInDevMode)
{
    WpfApplication1.MainWindow.inDevMode = true;
}
mainWindow.Show();

Upvotes: 3

Related Questions