1


I have a PropertyGrid which I use for a class which has a property that I would like to populate using an existing list of suitable values.

In order to achieve this I extend TypeConverter like this to show a drop down list:

public class BaseDefinitionTypeConverter : TypeConverter
{
    protected Dictionary<string, BaseDefinitionWrapper> mapping = new Dictionary<string, BaseDefinitionWrapper>();

    public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
        return true; // display drop
    }

    public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
        return true; // drop-down vs combo
    }

    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
        mapping.Clear();

        //Since everything is passed in as string a conversion is needed. "mapping" provides for that
        foreach (BaseDefinitionWrapper baseDef in BaseDefinitionWrapper.allWrappers) {
            mapping.Add(baseDef.ToString(), baseDef);
        }

        return new StandardValuesCollection(BaseDefinitionWrapper.allWrappers);
    }

    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
        //sourceType is ALWAYS string
        return sourceType == typeof(string);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
        //returns the actual selected object to the property grid. value is ALWAYS string.
        return mapping[value.ToString()];
    }
}

Used like:

[TypeConverter(typeof(BaseDefinitionTypeConverter))]
public BaseDefinitionTypeWrapper XYZ {
  get; set;
}

You can see that my backing list is BaseDefinitionWrapper.allWrappers.

Question #1) Why is sourceType in CanConvertFrom and value in ConvertFrom always string although the StandardValuesCollection is of a different type? Seems like the PropertyGrid only uses the toString() method of an element in the drop down list and passes that on.

I have the problem that the key value between the creation of the 'mapping' dictionary in "GetStandardValues" (baseDef.toString()) and the call to 'mapping' in "ConvertFrom" (value.ToString()) the actual value of the key (in the parameter 'value') can change(!) thus leading to an exception since the key could not be found. The object behind however does not change!

Question #2) How can I get the selected object from the drop down list whitout having to convert it from string which is not always possible (see above)? Is there a way to get the selected index of this drop down box as some kind of workaround?

Thank you very much!

1
  • OK, I eliminated the error by not allowing the contents of the drop down box to change in between. But the questions remain!
    – 8192K
    Nov 9, 2012 at 8:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.