2009-05-26 102 views
9

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

猜你沒明白我的意思是通過靜態類...想我會有更多的下一次闡述。 – CSharpAtl 2009-05-26 13:05:45

+0

字典不是線程安全的,如果您計劃從多個線程訪問ApplicationState,這將不是一個可行的解決方案。 – 2012-01-11 00:44:46

+0

@ J.Mitchell他可以使用ConcurrentDictionary – 2013-12-05 16:21:03

回答

9

這樣的事情應該工作。

public static class ApplicationState 
{ 
    private static Dictionary<string, object> _values = 
       new 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]; 
    } 
} 
+0

我們要在哪裏實現這個類?這是實現線程安全嗎? – Kalanamith 2016-06-03 05:14:55

0

只能將它自己存儲在靜態類中或者可以注入需要數據的類的存儲庫。

2

您可以公開App.xaml.cs文件中的公共靜態變量,然後使用App類的任何地方訪問它..

12

The Application class已經內置了這個功能。

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