在应用程序设置中保存自定义对象的集合

时间:2013-05-07 13:25:10

标签: wpf observablecollection settings.settings

我跟着Trouble saving a collection of objects in Application Settings保存了我在应用程序设置中绑定到DataGrid的自定义对象的ObservableCollection,但数据并没有像其他设置一样存储在user.config中。 有人可以帮我这个吗? 谢谢!

我的自定义类:

[Serializable()]
public class ActuatorParameter
{
    public ActuatorParameter()
    {}
    public string caption { get; set; }
    public int value { get; set; }
    public IntRange range { get; set; }
    public int defaultValue { get; set; }
}

[Serializable()]
public class IntRange
{
    public int Max { get; set; }
    public int Min { get; set; }

    public IntRange(int min, int max)
    {
        Max = max;
        Min = min;
    }
    public bool isInRange(int value)
    {
        if (value < Min || value > Max)
            return true;
        else
            return false;
    }
}

填写收集并保存:

Settings.Default.pi_parameters = new ObservableCollection<ActuatorParameter> 
{ 
new ActuatorParameter() { caption = "Velocity", range = new IntRange(1, 100000), defaultValue = 90000},
new ActuatorParameter() { caption = "Acceleration", range = new IntRange(1000, 1200000), defaultValue = 600000},
new ActuatorParameter() { caption = "P-Term", range = new IntRange(150, 350), defaultValue = 320},
new ActuatorParameter() { caption = "I-Term", range = new IntRange(0, 60), defaultValue = 30},
new ActuatorParameter() { caption = "D-Term", range = new IntRange(0, 1200), defaultValue = 500},
new ActuatorParameter() { caption = "I-Limit", range = new IntRange(0, 1000000), defaultValue = 2000}
};
Settings.Default.Save();

我的自定义设置:

internal sealed partial class Settings
{
    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    public ObservableCollection<ActuatorParameter> pi_parameters
    {
        get
        {
            return ((ObservableCollection<ActuatorParameter>)(this["pi_parameters"]));
        }
        set
        {
            this["pi_parameters"] = value;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

经过长时间的研究,我终于发现IntRange类缺少标准的构造函数。

[序列化()]

public class IntRange
{
    public int Max { get; set; }
    public int Min { get; set; }

    public IntRange()
    {}

    public IntRange(int min, int max)
    {
        Max = max;
        Min = min;
    }
   public bool isInRange(int value)
   {
        if (value < Min || value > Max)
            return true;
        else
            return false;
   }
}
相关问题