https://www.codeproject.com/Tips/48015/Exploring-the-Behaviour-of-Property-Grid
Hiding a Property from Property Grid at Runtime
The attributes of a property can be set as read-only in runtime for property grid using a
PropertyDescriptor
. User can set it either in a member function of a class or in a get{} set{}
section of property. The following code sets the readonly attribute of a property “DataType
” to true
. In the same way, the user can set it as false
.
Hide Copy Code
PropertyDescriptor descriptor =
TypeDescriptor.GetProperties(this.GetType())["DataType"];
ReadOnlyAttribute attrib =
(ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
FieldInfo isReadOnly =
attrib.GetType().GetField("isReadOnly", BindingFlags.NonPublic| BindingFlags.Instance);
isReadOnly.SetValue(attrib, true);
Note:
ReadOnlyAttribute
of all the properties must be set before, like [ReadOnlyAttribute(true)]
, while writing the class. Otherwise, the above code will set all the property’s attributes to true
.
In the same way, the
Browsable
attribute of any property can be set at runtime using PropertyDescriptor
. Here is the code:
Hide Copy Code
PropertyDescriptor descriptor=
TypeDescriptor.GetProperties(this.GetType())["DataType"];
BrowsableAttribute attrib=
(BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo isBrow =
attrib.GetType().GetField("browsable",BindingFlags.NonPublic | BindingFlags.Instance);
isBrow.SetValue(attrib,false);
The point to remember in both the cases is that all the attributes must be set for all properties, otherwise it will refresh all the properties of the class.