How to modify PropertyGrid at runtime (add/remove property and dynamic types/enums)

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 19:04:48

What you do, is adding StatesList (a TypeConverter) as a property.
What you should do, is adding a property with StatesList as its TypeConverter.

Ah, of course!

myProperties.Add(new CustomProperty("Custom", "", typeof(States), false, true));

[TypeConverter(typeof(StatesList))]
public class States
{
}

Works like a charm, thank you!

I have updated my project, hope it can be helpful to others, it can be found here.

Scott

This question and answer was of great usefulness to me. However, I needed to extend things a bit further by allowing for run-time generated dropdown list values. I thought I would post some sample code in regards to what it required, in case anyone finds it useful.

First, I added an options parameter to the CustomProperty constructor and added an Options property:

    private List<string> lOptions;

    public CustomProperty(string sName, object value, Type tType, bool bReadOnly, bool bVisible, List<string> lOptions)
    {
        this.lOptions = lOptions;
    }

    public List<string> Options
    {
        get { return lOptions; }
    }

Second, I added an Options property to the CustomPropertyDescriptor class:

    public List<string> Options
    {
        get
        {
            return m_Property.Options;
        }
    }

Third, I had to modify the GetStandardValues method in my dynamic type class (i.e. StatesList) to make use of the new Options property on the CustomPropertyDescriptor Object:

    public override StandardValuesCollection
                 GetStandardValues(ITypeDescriptorContext context)
    {
        CustomPropertyDescriptor descriptor = (CustomPropertyDescriptor)context.PropertyDescriptor;
        return new StandardValuesCollection(descriptor.Options);
    }

Finally, I had to pass in my list of options when creating a new CustomProperty object:

    List<string> optionsList = new List<string>(new string[] { "test1", "test2", "test3" });        
    CustomProperty myProperty = new CustomProperty(attr.Name, attr.Value, valueType, false, true, optionsList);

In place of the static list that I passed in for this example, you can generate the list of options for your dropdown in any manner that you please, giving you full control over the options available.

in my case TypeConverter did not apply to States class

[TypeConverter(typeof(StatesList))] // not work
public class States
{
}

so i added override in CustomPropertyDescriptor

public override TypeConverter Converter
{
    get {
        if (this.PropertyType.Equals(typeof(States)) ) {
            return new StatesList(); ; 
        }
        return base.Converter;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!