ICustomTypeDescriptor和XAML序列化
本文关键字:序列化 XAML ICustomTypeDescriptor | 更新日期: 2023-09-27 18:09:34
我有一个可以通过PropertyGrid编辑的业务对象。它包含一个标签列表(为了简化,我们称之为字符串)。
public class MyObject
{
// bunch of properties here, cut for readiness
public LabelsList List {get;set;}
// ...
}
标签列表是继承自List的简单类:
public class LabelsList : List<T>
{}
为了在属性网格中正确显示我的对象(我的意思是可扩展可编辑的标签列表),我已经为LabelsList实现了一个ICustomTypeDescriptor,显着改变GetProperties()方法:
public PropertyDescriptorCollection GetProperties()
{
var props = new PropertyDescriptorCollection(null);
for (var i = 0; i < this.Count; i++)
{
var descriptor = new LabelsListPropertyDescriptor(this, i);
props.Add(descriptor);
}
return props;
}
现在的问题-当我使用标准的XAML序列化通过调用XamlWriter.Save(this)对底层类型,它增加了过多的LabelsList。结果XAML:
内的LabelName标签<wpfdl:LabelsList>
*<wpfdl:LabelsList.Label1Name>*
<wpfdl:Label LabelText="Label1Name"/>
*</wpfdl:LabelsList.Label1Name>*
...
</wpfdl:LabelsList>
这实际上禁用了以下(MyObject)XamlReader.Parse(exportedXaml)调用,因为标签名称可以包含特殊字符。实现对象的正确编辑和序列化的适当解决方案是什么?提前感谢。
更新
通过更改各自的PropertyDescriptor:
public override bool ShouldSerializeValue(object component)
{
return false;
}
生成的xaml如下所示(原语是我的对象自定义类型的名称):
<Primitive>
<Primitive.Labels>
<Label LabelText="text1" LabelPosition="position1" />
<Label LabelText="text2" LabelPosition="position2" />
</Primitive.Labels>
</Primitive>
差不多了,但是现在
'Collection property 'WPF_DrawingsTest.Primitive'.'Labels' is null.' Line number '1' and line position '96'.
仍然需要使这个工作。也许测试项目将有助于看到我在寻找什么:
测试项目,100kb,无病毒
重构初始业务对象,序列化/反序列化现在自动完成并且工作良好。