在WPF中,我在哪裏可以在另一個一遍重視用戶控件訪問後保存的值在一個用戶控件的時候,那麼,類似的會話狀態中的網絡編程,如:如何在WPF中保存全局應用程序變量?
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");
猜你沒明白我的意思是通過靜態類...想我會有更多的下一次闡述。 – CSharpAtl 2009-05-26 13:05:45
字典不是線程安全的,如果您計劃從多個線程訪問ApplicationState,這將不是一個可行的解決方案。 – 2012-01-11 00:44:46
@ J.Mitchell他可以使用ConcurrentDictionary – 2013-12-05 16:21:03