如何在WPF中保存全局应用程序变量?

在WPF中,我可以在一个UserControl中保存值 ,然后在另一个UserControl 再次访问该值 ,例如Web编程中的会话状态,例如:

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 

回答:

谢谢,Bob,这是我开始工作的代码,基于你的代码:

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

要保存变量:

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

要读取变量:

 MainText.Text = ApplicationState.GetValue("currentCustomerName"); 

这样的事情应该有效。

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

Application类已经内置了此function。

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

您可以在App.xaml.cs文件中公开一个公共静态变量,然后使用App类在任何地方访问它。

可以将它自己存储在静态类或存储库中,您可以将其注入需要数据的类。