简体   繁体   中英

How do I make something happen in my windows phone 7 app only once?

I need to do something only once (in my case creating an instance of a class). The closest thing I can find is putting it in the PhoneApplicationPage_Loaded event handler, or at the top of MainPage.xaml. But this doesn't work for me because I have other pages in my app, so if I navigate from another page back to the MainPage it executes that code again.

Thanks, David

When you create a new project, you will find an App.xaml.cs file added to your project. Here you can add code that is executed at various points in your application lifecycle. You can add code to the method thar handles the Launching event:

// 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
}

This code will be executed just once when you application launches.

What you need (I assume) is a singleton class:

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

    private Singleton()
    {
    }

    public static Singleton GetInstance()
    {
        return instance;
    }
}

Now calling Singleton.GetInstance() from anywhere guarantees that you will get the same instance everytime.

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