ICustomTypeDescriptor and XAML Serialization

415 views Asked by At

I have a business object that can be edited via 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 :

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 :

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 :

<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. 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 :

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

Resulting xaml is as follows (Primitive is name of my object custom type):

<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 :

'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

1

There are 1 answers

0
Jaded On BEST ANSWER

Refactored initial business object, serialization/deserialization now is done automatically and works fine.