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

前端之家收集整理的这篇文章主要介绍了c# – 如何在WPF中保存全局应用程序变量?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
WPF中,在一个UserControl中我可以在哪里保存一个值,然后在另一个UserControl中再次访问该值,类似Web程序中的会话状态,例如:

UserControl1.xaml.cs:

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

UserControl2.xaml.cs:

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

回答:

谢谢,鲍勃,这里是我根据你的工作的代码

  1. public static class ApplicationState
  2. {
  3. private static Dictionary<string,object> _values =
  4. new Dictionary<string,object>();
  5. public static void SetValue(string key,object value)
  6. {
  7. if (_values.ContainsKey(key))
  8. {
  9. _values.Remove(key);
  10. }
  11. _values.Add(key,value);
  12. }
  13. public static T GetValue<T>(string key)
  14. {
  15. if (_values.ContainsKey(key))
  16. {
  17. return (T)_values[key];
  18. }
  19. else
  20. {
  21. return default(T);
  22. }
  23. }
  24. }

要保存变量:

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

要读取变量:

  1. MainText.Text = ApplicationState.GetValue<string>("currentCustomerName");

解决方法

这样的事情应该有效.
  1. public static class ApplicationState
  2. {
  3. private static Dictionary<string,object>();
  4.  
  5. public static void SetValue(string key,object value)
  6. {
  7. _values.Add(key,value);
  8. }
  9.  
  10. public static T GetValue<T>(string key)
  11. {
  12. return (T)_values[key];
  13. }
  14. }

猜你在找的C#相关文章