Use a Single Object Reference Globally in a UWP Application

Sometimes you might want a single object reference that can be accessed from any page within your application.  Creating an instance of it on the App using App.Current may be appropriate.

In this example we’re using a string, but you could easily use a custom object of your own creation.

In the App.xaml.cs file:

sealed partial class App : Application
{
  public string SomeValue;

  /// <summary>
  /// Initializes the singleton application object. This is the first line of authored code
  /// executed, and as such is the logical equivalent of main() or WinMain().
  /// </summary>
  public App()
  {
    this.InitializeComponent();
    this.Suspending += OnSuspending;

    // Do any initiation work here - just don't break the app 
    // or do anything that will slow it down too much.
    SomeValue = "New Value";
  }
}

To use in your code, e.g. on some page somewhere:

public sealed partial class SomePage : Page
{
  App _AppReference = App.Current as App;

  void SomeMethod()
  {
    _AppReference.SomeValue = "New Value";
  }
}

 

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s