如何在我的windows phone 7应用程序中只发生一次

本文关键字:一次 我的 windows phone 应用程序 | 更新日期: 2023-09-27 18:20:28

我只需要做一次(在我的例子中是创建一个类的实例)。我能找到的最接近的东西是把它放在PhoneApplicationPage_Loaded事件处理程序中,或者放在MainPage.xaml的顶部。但这对我来说不起作用,因为我的应用程序中还有其他页面,所以如果我从另一个页面导航回MainPage,它会再次执行该代码。

谢谢,David

如何在我的windows phone 7应用程序中只发生一次

当您创建一个新项目时,您会发现一个App.xaml.cs文件添加到您的项目中。在这里,您可以添加在应用程序生命周期中的各个点执行的代码。您可以向处理Launching事件的方法添加代码:

// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
   // your code goes here
}

当您的应用程序启动时,此代码将只执行一次。

您需要的(我假设)是一个singleton类:

public class Singleton
{
    private static Singleton instance = new Singleton();
    private Singleton()
    {
    }
    public static Singleton GetInstance()
    {
        return instance;
    }
}

现在,从任何地方调用Singleton.GetInstance()都可以保证每次都会得到相同的实例。