The article is mainly to explain how to make
PropertyGrid show only some properties of a class. One of the big limitations of this control is that it's not possible to hide or show any class properties at runtime.
For example, in an application that I'm developing, I had to show in the
PropertyGrid a class that inherits from
XMLElement, but I didn't want all the properties of the
XMLElement to be shown to the user. One solution was to create a new class that makes access to the main class, but this solution was too less expandable and not useful at runtime. So, I created this control that lets me control the properties shown in the
PropertyGrid at runtime too.
Using the code
The class to be shown in the
PropertyGrid must inherit from
ICustomClass which has only one property,
PublicProperties. This is a collection of
myProperty implements two properties:
Name: the name of the property to be shown.
Category: the name of the category to be shown in the
Adding a new property in the
Propertygrid is simple:
In this line, we want to show in the
PropertyGrid the property "
test3" in the category "Category1".
Now, to remove the property from the control:
Now, let's check the
PropertyGrid. The properties are visualized in the
PropertyTab object. So it's necessary to create a new
PropertyTab to access the visualized rows. To filter out the properties visualized, I've to override the
getProperties method of the
This method has an input parameter, the object to be shown in the
PropertyGrid. And this object must implement the
ICustomClass interface so that I can get the properties I want to display in the
PropertyGrid within the
To get all the properties of the selected object, there's the
TypeDescriptor.GetProperties(component). This function returns a
PropertyDescriptorCollection filled with all the properties of the class to be shown. But, as I said before, the class to be shown in the
PropertyGrid must implement
So with this row:
it's possible to retrieve the list of properties to be shown in the
PropertyTab. It's necessary to create a new
PropertyDescriptorfor for each new property.
PropertyDescriptor propArray =
Now I've to create the new property that will be shown in the
PropertyGrid. So I used
for (int i=0;i<bclass.PublicProperties.Count;i++)
arrProp[i] = TypeDescriptor.CreateProperty(prop.ComponentType, prop,
At the end of the loop, the
arrProp array will be filled up with the new property to be shown in the
PropertyTab. Now, since
Getproperties has a
PropertyDescriptorCollection as return parameter, we can create a new instance of it with:
The last step to get everything working, is to override the creation of the
PropertyTab of the
protected override PropertyTab CreatePropertyTab(Type tabType)
In this function, the base creation of the
Propertytab is bypassed, and only the filtered
Propertytab is created.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.