How can I save global application variables in WPF?

前端 未结 4 1053
既然无缘
既然无缘 2020-12-31 13:52

In WPF, where can I save a value when in one UserControl, then later in another UserControl access that value again, something like session

相关标签:
4条回答
  • 2020-12-31 14:08

    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];
        }
    }
    
    0 讨论(0)
  • 2020-12-31 14:12

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

    0 讨论(0)
  • 2020-12-31 14:19

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

    0 讨论(0)
  • 2020-12-31 14:33

    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"];
    
    0 讨论(0)
提交回复
热议问题