2

I have abstract class which have two child classes. Value, and StringValue or CustomValue. I want to create a converter to accept choose which class I need and serialize it well.

KOGRA
  • 43
  • 4

1 Answers1

2

There's a question with very good answer (But let me add more lines to make sure it accepts null values)

A Type Converter

 public class ValueConverter: SortedExpandableObjectConverter
    {
        private Value[] standardValues = new Value[3] { null, new StringValue(), new CustomValue()};
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string)) return true;
            return base.CanConvertFrom(context, sourceType);
        }
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            switch (value.ToString().Replace(" ", ""))
            {
                case "(None)":
                    return null;
                case nameof(StringValue):
                    return new StringValue();
                case nameof(CustomValue):
                    return new CustomValue();
            }
            return base.ConvertFrom(context, culture, value);
        }
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (value == null) return "(None)"; // to accept null value.
            return base.ConvertTo(context, culture, value, destinationType);
        }
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new StandardValuesCollection(standardValues);
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true;
        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => true;
    }

A classes

[TypeConverter(typeof(ValueConverter))]
public abstract class Value{}

public class StringValue : Value{ properties...}
public class CustomValue : Value{properties...}

   In UserControl declare property: 
   [DefaultValue(null)] // Is must for display null as grayed
   public Value MyValue{get;set;}
deveton
  • 291
  • 4
  • 26