
Populating a PropertyGrid using reflected types.
4Space,
I don't know if it can be done for a collection of objects but for one
object it can be done in the following way:
using System;
using System.ComponentModel;
using System.Windows.Forms;
// ...
// the PropertyGrid:
PropertyGrid pg = new PropertyGrid();
// some more initialization probably here....
// the object:
YourObject o1 = new YourObject();
// ...
pg.SelectedObject = o1;
// show only the DesignTime attributes
// (by default all the properties are DesignTime(false),
// so only the explicitly marked ones will be shown):
foreach(PropertyDescriptor pd in TypeDescriptor.GetProperties(o1))
{
if(((DesignOnlyAttribute)pd.Attributes[typeof(DesignOnlyAttribute)]).IsDesig
nOnly)
{
pg.BrowsableAttributes = new AttributeCollection(new Attribute[]{
pd.Attributes[typeof(DesignOnlyAttribute)]});
break;
}
Quote:
}
If you change the SelectedObject of the PropertyGrid, for the newly selected
object again only the DesignTime properties will be shown, i.e.:
SomeObject o2 = new SomeObject();
pg.SelectedObject = o2;
// only the DesignTime(true) properties will be shown
This may lead to the effect that this code could do what you need for the
collection of objects you need to be displayed, but I don't have time now to
test it, either to find it documented.
Also, the Browsable attribute is not taken in consideration, i.e. a
DesignOnly(true) and Browsable(false) property will be shown in the grid.
Hope this helps
Marty
Quote:
> > The property grid uses reflection to determine what to show in the
> grid,
> > so you shouldn't have a problem just setting it to your object. What do
> you
> > mean thought by not having a handle to a concrete object?
> > - Nicholas Paldino [.NET/C# MVP]
> Hi Nicholas.
> At runtime, the PropertyGrid is going to be pointed at a collection of
> 'System.Object's. Each object is of a completely different type, and with
a
> completely different interface. That's all it knows. It has to reflect on
> each object, and get a list of properties for it. Any properties that have
> the appropriate attribute on them should be displayed on the PropertyGrid.
> Can it be done?
> Cheers,
> 4Space