Edw*_*uay 10 c# wpf global-variables
在WPF中,我可以在一个UserControl中保存值,然后在另一个UserControl 中再次访问该值,例如Web编程中的会话状态,例如:
UserControl1.xaml.cs:
Customer customer = new Customer(12334);
ApplicationState.SetValue("currentCustomer", customer); //PSEUDO-CODE
Run Code Online (Sandbox Code Playgroud)
UserControl2.xaml.cs:
Customer customer = ApplicationState.GetValue("currentCustomer") as Customer; //PSEUDO-CODE
Run Code Online (Sandbox Code Playgroud)
谢谢,Bob,这是我开始工作的代码,基于你的代码:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
要保存变量:
ApplicationState.SetValue("currentCustomerName", "Jim Smith");
Run Code Online (Sandbox Code Playgroud)
要读取变量:
MainText.Text = ApplicationState.GetValue<string>("currentCustomerName");
Run Code Online (Sandbox Code Playgroud)
小智 14
Application类已经内置了此功能.
// Set an application-scope resource
Application.Current.Resources["ApplicationScopeResource"] = Brushes.White;
...
// Get an application-scope resource
Brush whiteBrush = (Brush)Application.Current.Resources["ApplicationScopeResource"];
Run Code Online (Sandbox Code Playgroud)
这样的事情应该有效.
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];
}
}
Run Code Online (Sandbox Code Playgroud)