Reputation: 878
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.
Upvotes: 0
Views: 156
Reputation: 138776
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; }
}
Upvotes: 0
Reputation: 1062550
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.
Upvotes: 1