이 블로그 검색

2018년 7월 11일 수요일

PropertyGrid 속성 감추기, 보여주기 / 활성화 비활성화

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.
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);
NoteReadOnlyAttribute 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:
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.

About the Author

Bhasker Kandpal
Architect IDS, Roma Italy
India India
Author has been working in software engineering and research since few years. The author worked and published a markable work in instrument interfacing techniques for 1m class telescopes. He is currently worki