gpt4 book ai didi

c# - 如何在 WPF 中保存全局应用程序变量?

转载 作者:可可西里 更新时间:2023-11-01 08:55:01 27 4
gpt4 key购买 nike

在 WPF 中,我可以在一个 UserControl 中保存值,然后在另一个 UserControl 中再次访问该值,类似于网络编程中的 session 状态,例如:

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

最佳答案

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"];

关于c# - 如何在 WPF 中保存全局应用程序变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/910421/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com