C# 如何在 WPF 中保存全局应用程序变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/910421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I save global application variables in WPF?
提问by Edward Tanguay
In WPF, where can I save a valuewhen in one UserControl, then later in another UserControl access that valueagain, something like session state in web programming, e.g.:
在 WPF 中,我可以在一个 UserControl 中保存值,然后在另一个 UserControl中再次访问该值,例如 Web 编程中的会话状态,例如:
UserControl1.xaml.cs:
UserControl1.xaml.cs:
Customer customer = new Customer(12334);
ApplicationState.SetValue("currentCustomer", customer); //PSEUDO-CODE
UserControl2.xaml.cs:
UserControl2.xaml.cs:
Customer customer = ApplicationState.GetValue("currentCustomer") as Customer; //PSEUDO-CODE
ANSWER:
回答:
Thanks, Bob, here is the code that I got to work, based on yours:
谢谢,鲍勃,这是我开始工作的代码,基于你的:
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);
}
}
}
To save a variable:
要保存变量:
ApplicationState.SetValue("currentCustomerName", "Jim Smith");
To read a variable:
读取变量:
MainText.Text = ApplicationState.GetValue<string>("currentCustomerName");
采纳答案by Bob
Something like this should work.
像这样的事情应该有效。
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];
}
}
回答by CSharpAtl
Could just store it yourself in a static class or repository that you can inject to the classes that need the data.
可以自己将它存储在静态类或存储库中,您可以将其注入需要数据的类。
回答by Gulzar Nazim
You can expose a public static variable in App.xaml.cs file and then access it anywhere using App class..
您可以在 App.xaml.cs 文件中公开一个公共静态变量,然后使用 App 类在任何地方访问它。
回答by Bob
The Application classalready has this functionality built in.
Application 类已经内置了这个功能。
// Set an application-scope resource
Application.Current.Resources["ApplicationScopeResource"] = Brushes.White;
...
// Get an application-scope resource
Brush whiteBrush = (Brush)Application.Current.Resources["ApplicationScopeResource"];