How to create a serializer for serializing a collection of objects in WinForms?

I have a class:

public class Filter
{
    public Filter (string name, string value)
    {
        Name = name;
        Value = value;
    }

    public string Name {get; private set;}
    public string Value {get; set;}
}

And collection class:

public class FilterCollection : Collection<Filter>
{
   // code elided
}

My component class:

public class MyComponent : Component
{
    // ...

    [Editor(typeof(FilterEditor), typeof(UITypeEditor))]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public FilterCollection Filters { get; set; }

    // ...
}

The problem is that the collection is not properly serialized by the designer.

I am sure that I have something missing, but I do not know what.

ADDITIONAL INFORMATION

I would like the designer.cs file to have the following:

myComponent.Filters.Add (new Filter ("some name", "some value"));
myComponent.Filters.Add (new Filter ("other name", "other value"));

Is it possible?

+5
source share
1 answer

Ok, the problem is resolved.

I needed to use TypeConverter for my Filter class:

internal class FilterConverter : TypeConverter
{
    public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(InstanceDescriptor) || base.CanConvertTo (context, destinationType);
    }

    public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(InstanceDescriptor) && value is Filter)
        {
            ConstructorInfo constructor = typeof (Filter).GetConstructor (new[] {typeof (string), typeof (string)});

            var filter = value as Filter;
            var descriptor = new InstanceDescriptor (constructor, new[] {filter.Name, filter.Value}, true);

            return descriptor;
        }
        return base.ConvertTo (context, culture, value, destinationType);
    }
}

Then the converter is added to the Filter class as follows:

[TypeConverter(typeof(FilterConverter))]
public class Filter
{
    // ...
}

. , (isComplete) InstanceDescriptor true.

+3

All Articles