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

前端 未结 4 1944
我寻月下人不归
我寻月下人不归 2020-12-05 02:49

How do you modify a propertygrid at runtime in every way? I want to be able to add and remove properties and add \"dynamic types\", what I mean with that is a type that resu

4条回答
  •  难免孤独
    2020-12-05 03:28

    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 lOptions;
    
        public CustomProperty(string sName, object value, Type tType, bool bReadOnly, bool bVisible, List lOptions)
        {
            this.lOptions = lOptions;
        }
    
        public List Options
        {
            get { return lOptions; }
        }
    

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

        public List 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 optionsList = new List(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.

提交回复
热议问题