Access to application members?

Suppose in App.cs - I would add a field to the class representing the application. Can I access this field from the application pages? If so, how can I do this? Am I correct in assuming that, once initialized, this element field will be "live" for the duration of the application?

+2


source to share


3 answers


You can. basically you just get the current app and send it to the App (or whatever, the class name is in your App.Xaml). Here's a snippet demonstrating this.

var myApp = Application.Current as App;
var n = myApp.NameOfPropertyAdded;

      



I'm not sure what you mean by live. I am assuming you want to bind stuff to it and update your bindings when you update it. To do this, you will need to set up a property change notification.

The approach of adding properties to the App.xaml.cs file smells a little funny to me. I think the recommended approach is to add the app to the app as an app-level resource so you can easily reference them in XAML.

+3


source


If you intend to access these fields frequently, it may be helpful to add a property for the current application to your ViewModel or Xaml.cs for easier access later.

public Application CurrentApp
{
    get
    {
        return Application.Current as App;
    }
}

      

Then in your page you can just link to your property



CurrentApp.MyField;

      

And yes, a field or property in your App.xamls.cs will last for the lifetime of the application.

+1


source


If you create a field, property, method static, then you can access it using

App.myField;
App.MyProperty;
App.MyMethod();

      

0


source







All Articles