当前位置: 首页 > 编程语言 > C#

如何在WPF中保存全局应用程序变量?分享

时间:2023-04-11 02:43:59 C#

C#学习教程:如何在WPF中保存全局应用程序变量?分享♀?♀如何在WPF中保存全局应用程序变量? 在WPF中,我可以在一个UserControl中保存值 ,然后在另一个UserControl 中再次访问该值 ,例如Web编程中的会话状态,例如: 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 回答: 谢谢,Bob,这是我开始工作的代码,基于你的代码: public static class ApplicationState { private static Dictionary _values = new Dictionary(); public static void SetValue(string key, object value) { if (_values.ContainsKey(key)) { _values.Remove(key); } _values.Add(key, value); } public static T GetValue(string key) { if (_values.ContainsKey(key)) { return (T)_values[key]; } else { return default(T); } } } 要保存变量: ApplicationState.SetValue("currentCustomerName", "Jim Smith"); 要读取变量: MainText.Text = ApplicationState.GetValue("currentCustomerName"); 这样的事情应该有效。 public static class ApplicationState { private static Dictionary _values = new Dictionary(); public static void SetValue(string key, object value) { _values.Add(key, value); } public static T GetValue(string key) { return (T)_values[key]; } } Application类已经内置了此function。 // Set an application-scope resource Application.Current.Resources["ApplicationScopeResource"] = Brushes.White; ... // Get an application-scope resource Brush whiteBrush = (Brush)Application.Current.Resources["ApplicationScopeResource"]; 您可以在App.xaml.cs文件中公开一个公共静态变量,然后使用App类在任何地方访问它。 可以将它自己存储在静态类或存储库中,您可以将其注入需要数据的类。 上述就是C#学习教程:如何在WPF中保存全局应用程序变量?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注— 本文来自网络收集,不代表立场,如涉及侵权请点击右边联系管理员删除。如若转载,请注明出处: