0

I'm using the C# property grid to add new objects and change settings of a specific object. I need to know how to pass a a variable to the constructor using the Component Model. Reason why is because a parameter is required to correctly define the initial values of the chart object.

List<Chart> charts = new List<Chart>();
[Description("Charts")]
[Category("4. Collection Charts")]
[DisplayName("Charts")]
public List<Chart> _charts
{
    get { return charts; }
    set { charts = value ; }
}




public class Chart
{
    public static string collectionName = "";

     int chartPosition = GetMaxChartIndex(collectionName);
     [Description("Chart posiion in document")]
     [Category("Control Chart Settings")]
     [DisplayName("Chart Position")]
     public int _chartPosition
     {
         get { return chartPosition; }
         set { chartPosition = value; }
     }


    public Chart(string _collectionName)
    {
        collectionName = _collectionName;

    }
}
ceds
  • 2,097
  • 5
  • 32
  • 50

1 Answers1

1

What you can do is declare a custom TypeDescriptionProvider for the Chart type, early before you select your object into the PropertyGrid:

...
TypeDescriptor.AddProvider(new ChartDescriptionProvider(), typeof(Chart));
...

And here is the custom provider (you'll need to implement the CreateInstance method):

public class ChartDescriptionProvider : TypeDescriptionProvider
{
    private static TypeDescriptionProvider _baseProvider = TypeDescriptor.GetProvider(typeof(Chart));

    public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args)
    {
        // TODO: implement this
        return new Chart(...);
    }

    public override IDictionary GetCache(object instance)
    {
        return _baseProvider.GetCache(instance);
    }

    public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance)
    {
        return _baseProvider.GetExtendedTypeDescriptor(instance);
    }

    public override string GetFullComponentName(object component)
    {
        return _baseProvider.GetFullComponentName(component);
    }

    public override Type GetReflectionType(Type objectType, object instance)
    {
        return _baseProvider.GetReflectionType(objectType, instance);
    }

    public override Type GetRuntimeType(Type reflectionType)
    {
        return _baseProvider.GetRuntimeType(reflectionType);
    }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        return _baseProvider.GetTypeDescriptor(objectType, instance);
    }

    public override bool IsSupportedType(Type type)
    {
        return _baseProvider.IsSupportedType(type);
    }
}
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298