10

在 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

回答:

谢谢,鲍勃,这是我根据你的代码开始工作的代码:

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

4 回答 4

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"];
于 2009-05-26T13:42:34.900 回答
9

像这样的东西应该工作。

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];
    }
}
于 2009-05-26T12:39:36.757 回答
2

您可以在 App.xaml.cs 文件中公开一个公共静态变量,然后使用 App 类在任何地方访问它。

于 2009-05-26T12:33:25.770 回答
0

可以自己将其存储在静态类或存储库中,您可以将其注入到需要数据的类中。

于 2009-05-26T12:29:57.650 回答