How can I save global application variables in WPF?

16,466

Solution 1

Something like this should work.

public static class ApplicationState 
{ 
    private static Dictionary<string, object> _values =
               new Dictionary<string, object>();

    public static void SetValue(string key, object value) 
    {
        _values.Add(key, value);
    }

    public static T GetValue<T>(string key) 
    {
        return (T)_values[key];
    }
}

Solution 2

You can expose a public static variable in App.xaml.cs file and then access it anywhere using App class..

Share:
16,466
Angry Dan
Author by

Angry Dan

web/software developer, .NET, C#, WPF, PHP, software trainer, English teacher, have philosophy degree, love languages, run marathons my tweets: http://www.twitter.com/edward_tanguay my runs: http://www.tanguay.info/run my code: http://www.tanguay.info/web my publications: PHP 5.3 training video (8 hours, video2brain) my projects: http://www.tanguay.info

Updated on July 06, 2022

Comments

  • Angry Dan
    Angry Dan almost 2 years

    In WPF, where can I save a value when in one UserControl, then later in another UserControl access that value again, something like session state in web programming, e.g.:

    UserControl1.xaml.cs:

    Customer customer = new Customer(12334);
    ApplicationState.SetValue("currentCustomer", customer); //PSEUDO-CODE
    

    UserControl2.xaml.cs:

    Customer customer = ApplicationState.GetValue("currentCustomer") as Customer; //PSEUDO-CODE
    

    ANSWER:

    Thanks, Bob, here is the code that I got to work, based on yours:

    public static class ApplicationState
    {
        private static Dictionary<string, object> _values =
                   new Dictionary<string, object>();
        public static void SetValue(string key, object value)
        {
            if (_values.ContainsKey(key))
            {
                _values.Remove(key);
            }
            _values.Add(key, value);
        }
        public static T GetValue<T>(string key)
        {
            if (_values.ContainsKey(key))
            {
                return (T)_values[key];
            }
            else
            {
                return default(T);
            }
        }
    }
    

    To save a variable:

    ApplicationState.SetValue("currentCustomerName", "Jim Smith");
    

    To read a variable:

    MainText.Text = ApplicationState.GetValue<string>("currentCustomerName");
    
  • 0x12
    0x12 almost 8 years
    Where do we going to implement this class? and is this implementation Thread Safe ?