在
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
回答:
谢谢,鲍勃,这里是我根据你的工作的代码:
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); } } }
要保存变量:
ApplicationState.SetValue("currentCustomerName","Jim Smith");
要读取变量:
MainText.Text = ApplicationState.GetValue<string>("currentCustomerName");
解决方法
这样的事情应该有效.
public static class ApplicationState { private static 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]; } }