How can I save global application variables in WPF?

眉间皱痕 提交于 2019-12-18 13:16:32

问题


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");

回答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];
    }
}



回答2:


The Application class already has this functionality built in.

// Set an application-scope resource
Application.Current.Resources["ApplicationScopeResource"] = Brushes.White;
...
// Get an application-scope resource
Brush whiteBrush = (Brush)Application.Current.Resources["ApplicationScopeResource"];



回答3:


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




回答4:


Could just store it yourself in a static class or repository that you can inject to the classes that need the data.



来源:https://stackoverflow.com/questions/910421/how-can-i-save-global-application-variables-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!