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