重新启动应用程序后事件为null

本文关键字:null 事件 应用程序 重新启动 | 更新日期: 2023-09-27 18:28:11

current我的App.xaml.cs 中有一个事件

    public partial class App : Application
    {
        public static event EventHandler SettingsSaved;
        private async void Application_Launching(object sender, LaunchingEventArgs e)
        {
            if (SettingsSaved != null)
            {
                SettingsSaved(this, null);
            }
     }

以及在我的MainPage.xaml.cs 中

    public MainPage()
    {        
        InitializeComponent();
        App.SettingsSaved += App_SettingsSaved;
    }
    void App_SettingsSaved(object sender, EventArgs e)
    {
         //do something here
    }

第一次启动应用程序时,SettingsSaved工作正常,但第二次启动应用时,SettingsSave变为null。有没有办法确保保存的设置与第一次启动应用程序时相同?

我是一个程序员新手,我很确定我在这里错过了一些真正基本的东西。

重新启动应用程序后事件为null

与其把它放在公共MainPage()中,不如试着把它放进App.Initialize事件中,以确保它在启动时绝对发生。

我想我解决了这个问题。我相信我必须先订阅该事件,然后才能触发该事件,在我上面的代码中,我无法先订阅它,因为App.xaml.cs是在我可以在Mainpage.xaml.css中订阅它之前先执行的。

这对我第一次启动应用程序时很有效,因为我有一些额外的代码在等待。

我的解决方案更像是一个黑客攻击,我等待这样一个延迟的任务:

public partial class App : Application
{
    public static event EventHandler SettingsSaved;
    private async void Application_Launching(object sender, LaunchingEventArgs e)
    {
        //this await will cause the thread to jump to MainPage to subscribe to SettingsSaved event.
        await Task.Delay(500);
        if (SettingsSaved != null)
        {
            SettingsSaved(this, null);
        }
 }

当然,如果有人能想出一个更优雅的解决方案,在继续使用App.xaml.cs

中的代码之前,可以先初始化MainPage,我将不胜感激