简体   繁体   English

ICustomTypeDescriptor和XAML序列化

[英]ICustomTypeDescriptor and XAML Serialization

I have a business object that can be edited via PropertyGrid. 我有一个可以通过PropertyGrid编辑的业务对象。 It contains list of labels (let's say strings for simplification). 它包含标签列表(为简化起见,假设使用字符串)。

public class MyObject
{
    // bunch of properties here, cut for readiness
    public LabelsList List {get;set;}
    // ...
}

List of labels is simple class inherited from List : 标签列表是从List继承的简单类:

public class LabelsList : List<T>
{}

For proper displaying of my object in property grid (by that i mean expandable editable list of labels too) i've implemented an ICustomTypeDescriptor for LabelsList, changing notably GetProperties() method : 为了在属性网格中正确显示我的对象(也就是我也表示标签的可扩展可编辑列表),我为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;
}

Now the problem - when i use standard XAML serialization by calling XamlWriter.Save(this) on underlying type, it adds excessive LabelsList.LabelName tag inside resulting XAML : 现在的问题-当我通过对基础类型调用XamlWriter.Save(this)来使用标准XAML序列化时,会在生成的XAML内添加过多的LabelsList.LabelName标记:

<wpfdl:LabelsList>
    *<wpfdl:LabelsList.Label1Name>*
        <wpfdl:Label LabelText="Label1Name"/>
    *</wpfdl:LabelsList.Label1Name>*
...
</wpfdl:LabelsList>

That actually disables following (MyObject)XamlReader.Parse(exportedXaml) call because label names can contain special characters. 实际上,这会禁用以下(MyObject)XamlReader.Parse(exportedXaml)调用,因为标签名称可以包含特殊字符。 What is proper workaround to achieve both correct editing and serializing of objects? 有什么适当的解决方法可以同时实现对象的正确编辑和序列化? Thanks in advance. 提前致谢。
update 更新
Made unnecessary tags go away by changing respective PropertyDescriptor : 通过更改相应的PropertyDescriptor使不必要的标签消失:

public override bool ShouldSerializeValue(object component)
{
    return false;
}

Resulting xaml is as follows (Primitive is name of my object custom type): 结果xaml如下(原始是我的对象自定义类型的名称):

<Primitive>
    <Primitive.Labels>
        <Label LabelText="text1" LabelPosition="position1" />
        <Label LabelText="text2" LabelPosition="position2" />
    </Primitive.Labels>
</Primitive>

That's pretty much it, but now <LabelsList> tags inside <Primitive.Labels> are missing : 差不多了,但是现在<Primitive.Labels>中的<LabelsList>标签丢失了:

'Collection property 'WPF_DrawingsTest.Primitive'.'Labels' is null.' Line number '1' and line position '96'.

Still need to make this work. 仍然需要做这项工作。 Maybe test project will help to see what i'm looking for : 也许测试项目将有助于了解我在寻找什么:
Test project, 100 kb, no viruses 测试项目,100 kb,无病毒

重构的初始业务对象,序列化/反序列化现在可以自动完成并且可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM