Monday, August 15, 2011

Global Variables

Problem Scenario:

Need variables that can be global throughout the entire application. A couple examples of this may include knowing if the phone is connected to a network. I also utilize it for timing and scores in games so I can always show the scores and game time.

Step #1:


in app.xaml.cs

after #endregion of phone initialization

place this code:
#region Phone application initialization



#endregion

}

public partial class globalstuff

{

public int myprop1 { get; set; }



public static class GlobalVariables

{

public static int networkgood = 0;

public static string networksolid = "NO";




}

}





}





Step #2:


Now within your pages you create an actual instance that you can utilize throughout your application. Normally on main page I perform the following:



public MainPage()

{

InitializeComponent();



// create an instance of your global stuff



globalstuff myglobalstuff = new globalstuff();



}


Now anywhere in your application you can utilize your global variables, example:


globalstuff.GlobalVariables.networksolid = "YES"; // default


Then to perform checks and perform actions based on the variable:



if (globalstuff.GlobalVariables.networksolid == "NO")

{

textBlock2.Text += "No Network connection!!!";

textBlock3.Text += "No Network connection!!!";

}

else

{

textBlock3.Text = "Good Network Connection";

// textBlock3.Text += NetworkInterface.NetworkInterfaceType.ToString();

}




No comments:

Post a Comment