0

I created a class for my PropertyGrid control which looks something like this:

public class DetailFilterProperties 
{
    public DetailFilterProperties(TreeViewEventArgs e)
    {
              ...
    }

    [CategoryAttribute("Base"), DescriptionAttribute("Filtered fields referring to a formatted yam field"), ReadOnly(true)]
    public Dictionary<String, String> FilteredFields
    {
        get;
        set;
    }

    ...
}

At runtime i want to add a string property (or a list of strings) to my class can anyone give me an example of how to do this please.

I browsed the web and read about ExpandoObject but i bet there is an easier way to achieve this, I just didnt find an example yet.

thanks for your help in advance.

user3596113
  • 868
  • 14
  • 32

2 Answers2

1

You can't actually add a property to a C# class at runtime; however, PropertyGrid usually respects flexible types via ICustomTypeDescriptor. You can supply a custom type descriptor either by implementing that interface directly (lots of work), or by registring a TypeDescriptionProvider (also lots of work). In either case, you'll have to implement a custom PropertyDescriptor, and think of somewhere for the data to go.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

What you could do is reuse the DynamicTypeDescriptor class described in my answer to this question here on SO: PropertyGrid Browsable not found for entity framework created property, how to find it?

like this:

  ...
  MyDynamicClass c = new MyDynamicClass();
  c.MyStaticProperty = "hello";

  // build an object "type" from the original one
  DynamicTypeDescriptor dt = new DynamicTypeDescriptor(typeof(MyDynamicClass));

  // get a wrapped instance
  DynamicTypeDescriptor c2 = dt.FromComponent(c);

  // add a property named "MyDynamicProperty" of Int32 type, initial value is 1234
  c2.Properties.Add(new DynamicTypeDescriptor.DynamicProperty(dt, typeof(int), 1234, "MyDynamicProperty", null));

  propertyGrid1.SelectedObject = c2;
  ...

  // the class you want to "modify"
  public class MyDynamicClass
  {
      public string MyStaticProperty { get; set; }
  }
Community
  • 1
  • 1
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298