简体   繁体   中英

Passing reference of global object in App.xaml.cs

I am trying to implement a global object which stores every parameter that I can pass between pages. My object is called AppObject. I can declare it in my mainpage.xaml.cs and then pass it through reference using

Page.Navigate(typeof(anotherpage), AppObject);

However, I would like to save the objects to file through the on_suspending event. How can I pass this parameter to the on_suspending event or is there anyway for me to declare this AppObject in the app.xaml.cs and then pass it to the mainpage.xaml.cs?

My App.xaml.cs

AppObject AppObject = new AppObject();

    /// <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 += this.OnSuspending;
        Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
    }

...more code

    /// <summary>
    /// Invoked when application execution is being suspended.  Application state is saved
    /// without knowing whether the application will be terminated or resumed with the contents
    /// of memory still intact.
    /// </summary>
    /// <param name="sender">The source of the suspend request.</param>
    /// <param name="e">Details about the suspend request.</param>
    private async void OnSuspending(object sender, SuspendingEventArgs e)
    {
        var deferral = e.SuspendingOperation.GetDeferral();

        // TODO: Save application state and stop any background activity

        //I want to write to file here and be able to refereence to the AppObject which I pass around.

        deferral.Complete();
    }

In App.xaml.cs, make sure the objects you need are public. Say you have something like this:

public AppObject appObject = new AppObject();

Now, in MainPage.xaml.cs, you just have to create the objects of the same type you want to pass. Then, create another object that has the reference to the App like this:

var appReference = App.Current as App;
AppObject objectInMain = appReference.appObject;

Now you have another object in MainPage.xaml.cs, that is the exact copy of the one in App.xaml.cs. You've just effectively passed data between two pages. You can create a reference to the App in any page as shown above and use the variables declared in App.xaml.cs in that page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM