In Windows application development we need global variables which can be used across application and multiple forms (Form1, Form2, etc.). Below code shows how to create/access global variables using static class and singleton pattern.
Using Static Class:
public static class Global
{
public static string MyProperty{get;set;}
}
Usage:
string data = Global.MyProperty
Using Singleton Class:
Global class implements the Singleton pattern so that there is only one of Global class instances in the application.
public class Global
{
private static readonly Global instance = new Global();
public static Global Instance
{
get
{
return instance;
}
}
private Global()
{
}
public string MyProperty
{
get;
set;
}
}
Usage:
string data = Global.Instance.MyProperty
MVVM with Singleton:
Add below GlobalInstance property to your BaseViewModel class( class which inherited by all view-models).
public Global GlobalInstance
{
get { return Global.Instance; }
}
Usage:
<Label Content="{Binding GlobalInstance.MyProperty, Mode=OneWay}" ... />