[Serializable]
public class ProfilesCollection : ObservableCollection<Profile>
{
public ProfilesCollection()
{
}
}
[Serializable]
public class Profile : ObservableCollection<SomeData>
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
public Profile()
{
}
}
[Serializable]
public class SomeData : INotifyPropertyChanged
{
// some properties
public SomeData()
{ ... }
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
我正在尝试使用XmlSerializer序列化ProfilesCollection(或Profile)对象:
using (var writer = new StreamWriter("1.xml"))
{
var xs = new XmlSerializer(typeof(ProfilesCollection));
xs.Serialize(writer, _profiles);
}
但.xml不包含Profile类中的Name属性。除了那之外的一切都没问题。我该怎么做才能解决这个问题?
答案 0 :(得分:2)
当XmlSerializer
序列化集合时,它只查看集合中的项目,而不是集合类的其他属性。如果您需要序列化名称,则需要执行以下操作:
public class Profile
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
private readonly ObservableCollection<SomeData> _data = new ObservableCollection<SomeData>();
public ObservableCollection<SomeData> Data
{
get { return _data; }
}
public Profile()
{
}
}
顺便说一句,Serializable
未使用NonSerialized
和XmlSerializer
属性,因此您不需要它们(事件不会被XmlSerializer
序列化)< / p>
答案 1 :(得分:0)
我认为您的1.xml文件应该与Profile类具有相同的结构。 (它应该有一个Name节点?)