是否可以使用更简洁的XAML样式语法
通过XML序列化读取C#PointCollection<Points>1,2 3,4</Points>
而不是
<Points>
<Point>
<X>1</X>
<Y>2</Y>
</Point>
<Point>
<X>3</X>
<Y>4</Y>
</Point>
</Points>
虽然我使用下面的代码使后来的工作正常,但如果可能,我更愿意使用前者。
[XmlElement("Points")]
public PointCollection Points { get; set; }
答案 0 :(得分:0)
你可以使用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" />