Using .NET 4, C#
Let's say I have class Info
that extends CustomTypeDescriptor
. An instance of class Info
has a dictionary of <string, object>
pairs, loaded at runtime.
I'd like to be able to expose the dictionary keys as properties (so that each instance of Info
has different properties). The values of the properties should be the corresponding values in the dictionary.
I got around to exposing properties:
public override PropertyDescriptorCollection GetProperties()
{
var orig = base.GetProperties();
var newProps = dictionary.Select( kvp =>
TypeDescriptor.CreateProperty(
this.GetType(),
kvp.key,
typeof(string)));
return new PropertyDescriptorCollection(
orig.Cast<PropertyDescriptor>()
.Concat(newProps)
.ToArray());
}
The problem is, how do I get their values?
var info = new Info(new Dictionary<string, object>{{"some_property", 5}};
var prop = TypeDescriptor.GetProperties(i_info)["some_property"];
var val = prop.GetValue(i_info); //should return 5
The only way I found to get control when prop.GetValue()
is called was to override GetPropertyOwner(PropertyDescriptor pd)
, but the way I understand it, it expects me to return the instance of another type that has a matching real (compiled) property.
I'd like to be able to write the actual implementation of the property myself (for this example, return the value in the dictionary whose key matches the property name).
Is this possible?
You need to make your own implementation of the
PropertyDescriptor
class overridingGetValue
method. So instead ofTypeDescriptor.CreateProperty
you'll use newMyCoolPropertyDescriptor(dictionary, kvp.Key)
or like.Here is a sample of how it can be implemented: