Actually, TypeConverter.GetProperties is the exception for listing
properties; the "normal" approach is
TypeDescriptor.GetProperties(obj) or TypeDescriptor.GetProperties(obj,
attribs)
Note that neither requires a context - just a value - so you can
recurse i.e.
void ShowProps(object parentObj) {
foreach(PropertyDescriptor prop in
TypeDescriptor.GetProperties(obj)) {
object childObj = prop.GetValue(parentObj);
if(childObj != null) {
ShowProps(childObj);
}
// do something meaningful - i.e. WriteLine(prop.Name + "="
Convert.ToString(childObj));
}
}
Note, however, that for getting the string, the TypeConverter often
*is* the better approach (some conversions depend on the context); you
can write your own ITypeDescriptorContext class very easily (as
below), and use as:
Context ctx = new Context(parentObj, prop);
Make sense?
Marc
[ImmutableObject(true)]
public sealed class Context : ITypeDescriptorContext {
private readonly object component;
private readonly PropertyDescriptor property;
public Context(object component, PropertyDescriptor property)
{
this.component = component;
this.property = property;
}
IContainer ITypeDescriptorContext.Container {
get { return null; }
}
object ITypeDescriptorContext.Instance {
get { return component; }
}
void ITypeDescriptorContext.OnComponentChanged() {
}
bool ITypeDescriptorContext.OnComponentChanging() {
return true;
}
PropertyDescriptor ITypeDescriptorContext.PropertyDescriptor {
get { return property; }
}
object IServiceProvider.GetService(Type serviceType) {
return null;
}
}
I have an object which I present to the user through a propertyGrid. With
many of the properties (many of which are objects themselves) I have
implemented my own TypeConverters; many of these inherit from the
ExpandableObjectConverter so that child properties are available to the user.
That all works swell.
Now I'm trying to create a print engine that will be able to print all
properties (Browsable). I thought this was going to be straightforward but I
have hit a snag....
I want to be able to go through the properties of my object and access the
all the child objects and their properties (essentially expanding them for my
print output)
Using the TypeDescriptor.GetProperties() I am able to get a collection of
all the 'first level Properties. I thought that getting at the Child object
properties would be as simple as using the TypeDescriptor.GetConverter()
method. This returns the TypeConvertor but I do not know how to determine if
it is of the expandable variety.
I tried looking at how the property grid accomplishes this but am having
difficulty. It looks like it uses the GetPropertiesSupported() Method on the
TypeDescriptor to determine if the object is expandable. I am trying this by
overriding the GetPropertiesSupported(ITypeDescriptorContext context) method.
However I don't really understand where I get the context from. I need an
example.
If anyone can help it would be appreciated.