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

本文关键字:全局 对象 引用 App xaml cs | 更新日期: 2023-09-27 18:35:45

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

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

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

我的应用程序.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();
    }

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

在 App.xaml.cs 中,确保所需的对象是公共的。假设你有这样的东西:

public AppObject appObject = new AppObject();

现在,在 MainPage.xaml.cs 中,您只需创建要传递的相同类型的对象。然后,创建另一个引用应用程序的对象,如下所示:

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

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