2009-05-26 14 views
9

In WPF, dove posso salvare un valore quando in uno UserControl, poi in un altro UserControl di accesso che apprezzi di nuovo, qualcosa come lo stato della sessione in programmazione web, ad esempio:Come posso salvare le variabili globali dell'applicazione in 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 

RISPOSTA:

Grazie, Bob, ecco il codice che ho avuto modo di lavorare, in base alla vostra:

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); 
     } 
    } 
} 

Per salvare una variabile:

ApplicationState.SetValue("currentCustomerName", "Jim Smith"); 

Per leggere una variabile :

MainText.Text = ApplicationState.GetValue<string>("currentCustomerName"); 
+0

Immagino che tu non hai capito cosa intendevo per classe statica ... che dovrò elaborare più la prossima volta. – CSharpAtl

+0

Il dizionario non è thread-safe, questa non sarebbe una soluzione praticabile se si intende accedere a ApplicationState da più thread. –

+0

@ J.Mitchell Può usare ConcurrentDictionary –

risposta

9

Qualcosa del genere dovrebbe funzionare.

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

Dove implementeremo questa classe? ed è questo thread di implementazione sicuro? – Kalanamith

0

Potrebbe semplicemente memorizzarlo in una classe statica o repository che è possibile iniettare nelle classi che necessitano dei dati.

2

È possibile esporre una variabile statica pubblica nel file di App.xaml.cs e poi accedervi ovunque utilizzando classe App ..

12

The Application class ha già questa funzionalità incorporata.

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