0

In MainWindow.xaml.cs class, when trying to get access to my property Name inside App.xaml.cs class, I'm getting the error:

'App' does not contain a definition for 'Name'.

Why?

Remark: I'm working a scenario similar to this one. But author there is using a global variable, and as we know, in most cases, using properties is preferred over global variable. So, I'm trying property in my case.

App.xaml.cs:

public partial class App : Application
{
    private string[] name;
    public string[] Name
    {
        get { return name; }
        set { name = value; }
    }
}

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        string[] myArray = App.Name //VS2019 Intellisense gives the error: 'App' does not contain a definition for 'Name'
    }
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
nam
  • 21,967
  • 37
  • 158
  • 332
  • My bad, as `@TamBui` pointed it, I forgot to use the static keyword in the property declaration. More on the topic, interesting debate [here](https://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp). Specifically the [comment](https://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp#comment103027740_241339) from @ashveli. – nam May 27 '20 at 14:17

2 Answers2

1

You need to make the Name property static because it doesn't look like you are instantiating your App class inside your MainWindow class at all.

......
......
public partial class App : Application
{
    private static string[] name;
    public static string[] Name
    {
        get { return name; }
        set { name = value; }
    }
......
......
}
Tam Bui
  • 2,940
  • 2
  • 18
  • 27
0

public string[] Name is an instance property of App, so you need to get a reference to instance before accesing data.

the running WPF instance can be obtained from static property Application.Current (requires cast)

var app = Application.Current as App;
string[] myArray = app.Name;
ASh
  • 34,632
  • 9
  • 60
  • 82