您可以使用System.Xml.Serialization.XmlSerializer:
[XmlIgnore]
public PointCollection Points { get; set; }
[XmlElement("Points")]
public string FakePoints
{
get { return string.Join(" ", Points.Select(p => p.X + "," + p.Y)); }
set
{
var collection = new PointCollection();
foreach (var s in value.Split())
{
var p = s.Split(',');
collection.Add(new Point { X = int.Parse(p[0]), Y = int.Parse(p[1]) });
}
Points = collection;
}
}
我不知道您的 PointCollection 和 Point 类的确切类型。或许代码可以稍微简化一下。
如果您使用System.Windows.Media.PointCollection 和System.Windows.Point,那么您可以使用System.Xaml.XamlServices 类获得所需的结果。
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Xaml;
public class Foo
{
public PointCollection Points { get; set; }
}
var foo = new Foo
{
Points = new PointCollection()
{
new Point { X = 1, Y = 2 },
new Point { X = 3, Y = 4 }
}
};
using (var fs = new FileStream("test.xml", FileMode.Create))
XamlServices.Save(fs, foo);
using (var fs = new FileStream("test.xml", FileMode.Open))
foo = (Foo)XamlServices.Load(fs);
结果:
<Foo Points="1,2 3,4" xmlns="clr-namespace:;assembly=ConApp" />