DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

Global variables in WPF/WinForms/MVVM

By Ashok Nalam on 12 Dec 2013 | Category: WPF | Tagged: .NET variable 
  Discuss Add Comment   |  
Add rating Rate this resource   
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}" ... />
  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9526  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (2)
 
1. By ZAP on 23 Oct 2023

 
2. By ZAP on 23 Oct 2023

 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys