在App.xaml.cs中传递全局对象的引用

时间:2014-12-29 18:36:00

标签: c# windows-phone-8.1

我正在尝试实现一个全局对象,它存储我可以在页面之间传递的每个参数。我的对象叫做AppObject。我可以在我的mainpage.xaml.cs中声明它,然后使用

通过引用传递它
Page.Navigate(typeof(anotherpage), AppObject);

但是,我想通过on_suspending事件将对象保存到文件中。如何将此参数传递给on_suspending事件,或者我是否在app.xaml.cs中声明此AppObject,然后将其传递给mainpage.xaml.cs?

我的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();
    }

1 个答案:

答案 0 :(得分:0)

在App.xaml.cs中,确保您需要的对象是公共的。说你有这样的事情:

public AppObject appObject = new AppObject();

现在,在MainPage.xaml.cs中,您只需要创建要传递的相同类型的对象。然后,创建另一个具有对App的引用的对象:

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

现在你在MainPage.xaml.cs中有另一个对象,它是App.xaml.cs中的一个对象的精确副本。您只是在两个页面之间有效地传递数据。您可以在任何页面中创建对App的引用,如上所示,并使用该页面中App.xaml.cs中声明的变量。