Question

Let's assume that In the App.cs - I'd add a field to the class representing the application. Can I access that field from the app's pages? If so, how can I do that? Am I correct to assume that once initialized this member field would be "alive" for the duration of the application's runtime ?

Was it helpful?

Solution

You can. basically you just get the current application and cast it to App (or whatever the name of the class is in your App.Xaml). Here is a snippet demonstrating that.

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

I am not sure what you mean by alive. I will assume that you want to bind stuff to it and have your bindings update when it updates. To do that you'll need to set up the property change notification.

The approach of adding properties to the App.xaml.cs file smells a little funny to me. I think that the reccomended approach would be to add thing to the application as an application level resource so that you can easily reference them in XAML.

OTHER TIPS

If you are going to be accessing these fields frequently, it can be useful to add a property for the current application in either your ViewModel or Xaml.cs for easy access later.

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

Then in your page, you can just reference your property

CurrentApp.MyField;

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

If you make the field, property, method static, then you can access it using

App.myField;
App.MyProperty;
App.MyMethod();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top