2

From this question WinForms designer properties of different derived types Answer by @Reza Aghaei is very good.

But about make value = null. Yes its done by following. But the WinForms Designer doesn't show (Null) literal string.

Here's implementation

public class ValueElementConverter : ExpandableObjectConverter
{
    ValueElement[] standardValues = new ValueElement[] { null, new StaticValue(), new DynamicValue() };
    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)
    {
        if (value == null) return null;
        if (value.ToString().Trim().Length == 0)
            return null;
        else
        {
            var result = standardValues.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x?.ToString()) && x.ToString() == value?.ToString());
            if (result != null)
                return result;
            return base.ConvertFrom(context, culture, value);
        }
    }
    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
    {
        return true;
    }
    public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
    {
        return true;
    }        

    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        List<ValueElement> xx = new List<ValueElement>();
        return new StandardValuesCollection(standardValues);
    }

}

[TypeConverter(typeof(ValueElementConverter))]
public abstract class ValueElement
{
}

public class StaticValue : ValueElement
{
    public string value { get; set; }

    public override string ToString()
    {
        return "Static";
    }
}

public class DynamicValue : ValueElement
{
    public string dynamicValue;

    public override string ToString()
    {
        return "Dynamic";
    }
}

Here's result. awesome except first value which is null in standardValues collection. but doesn't show Null string literal in Visual Studio WinForms designer.

See Image

orlgro
  • 29
  • 5
  • 3
    Please some ping @Reza Aghaei during my reputations I can't post or comments. Here's old answer link https://stackoverflow.com/questions/37931785/winforms-designer-properties-of-different-derived-types – orlgro Apr 27 '21 at 20:05
  • override ConvertTo() and check for if value is null return "(none)" then inside ConvertFrom handle if value == "(none") then return null; else return your values. – deveton May 31 '21 at 03:11

0 Answers0