2009-05-26 104 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"]; 
相关问题